clickable drawable inside EditText in android

烂漫一生 提交于 2019-12-07 13:58:01

问题


I have an EditText with a drawable inside. I want to make the drawable clickable so that I can have a specific action when user clicks the drawable. How do I do that? My EditText is:

<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" />

回答1:


As Gina suggested above, you can achieve this by using RelativeLayout instead of drawableRight property. Code below puts the imageview to the right part of your 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>



回答2:


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;
        }
    });


来源:https://stackoverflow.com/questions/17558072/clickable-drawable-inside-edittext-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!