Android中EditText内的可点击绘图

3

我有一个带着drawable的EditText。我想让这个drawable可以被点击,以便当用户点击它时,我能够执行特定的操作。 我该如何实现?我的EditText代码如下:

<EditText
        android:id="@+id/phone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="5dp"
        android:drawableRight="@drawable/question_mark"
        android:hint="phone number"
        android:imeActionId="@+id/phone_num"
        android:maxLines="1"
        android:singleLine="true"
        android:textColor="#000000" />

为什么不用 ImageView 而是用 EditText?添加一个 android:onClick="phoneClicked" 属性,然后实现 public void phoneClicked( View view ) {...} - LuckyMe
我的设计要求问号图像出现在EditText视图内部。 - Cote Mounyo
据我所知,你不能这样做,你需要创建一个带有白色背景的容器,并在旁边添加EditText和Image,然后使Image具有onClick事件。换句话说,你会给人一种图像在文本区域内的错觉,但实际上并不是这样。如果有人知道我错了,请指正我。 - LuckyMe
RelativeLayout 可能允许您将按钮放置在 EditText 的上方/下方。 - Gina
2个回答

4

正如Gina上面建议的那样,你可以使用RelativeLayout而不是drawableRight属性来实现这一点。下面的代码将图像视图放置在EditText的右侧部分。

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

<EditText
    android:id="@+id/phone"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginBottom="5dp"
    android:hint="phone number"
    android:imeActionId="@+id/phone_num"
    android:maxLines="1"
    android:singleLine="true"
    android:textColor="#000000" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_alignRight="@+id/phone"
        android:layout_marginRight="10dp"
        android:layout_centerVertical="true"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>

我知道如何做这个。我一直在寻找更简单的方法。但在有人提供更好的答案之前,我会接受这个答案。 - Cote Mounyo
1
这个不正常,文本会被图片覆盖。在高标准的应用程序中是不可接受的。 - user1545072
2
如果你在EditText右侧添加40dp的padding(使用我提供的代码),它将正常工作。这样文本就会在图片之前结束,它们不会重叠。 - canova
你也可以使用 android:layout_alignLeft="@+id/imageView1" 来使其与父容器匹配。 - Aklesh Singh

1
phone.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            final int DRAWABLE_RIGHT = 2;

            if(motionEvent.getAction() == MotionEvent.ACTION_UP) {
                if(motionEvent.getRawX() >= (phone.getRight() - phone.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
                    //Here is your code when you click drawable right
                    return true;
                }
            }
            return false;
        }
    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接