3

我有一个 EditText,里面有一个 drawable。我想让drawable可点击,这样当用户点击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" />
4

2 回答 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>
于 2013-07-10T08:18:33.270 回答
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;
        }
    });
于 2019-07-02T13:44:38.123 回答