Click listener for drawableleft in EditText in Android?

青春壹個敷衍的年華 提交于 2019-12-19 04:09:30

问题


Is it possible to add a OnClickListener to on a drawable that is declared in designer as drawableleft

android:drawableLeft="@drawable/ic_password"

Or is there any way to add a ImageView on the left side of that EditText


回答1:


For drawableleft click listeners:

 editText.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        final int DRAWABLE_LEFT = 0;
        final int DRAWABLE_TOP = 1;
        final int DRAWABLE_RIGHT = 2;
        final int DRAWABLE_BOTTOM = 3;

       if(event.getRawX() <= (editText.getCompoundDrawables()[DRAWABLE_LEFT].getBounds().width()))
        {
              // your action here
             return true;
        }
        return false;
    }
});

In case if you want click listener for drawable right use following condition

if(event.getAction() == MotionEvent.ACTION_UP) {
            if(event.getRawX() >= (editComment.getRight() - editComment.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) 



回答2:


You can achieve it by a RelativeLayout:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="16dp">

    <ImageView
        android:id="@+id/image_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerInParent="true"
        android:src="@drawable/ic_iamge"/>

    <EditText
        android:id="@+id/text_id"
        android:layout_toRightOf="@id/image_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_marginLeft="16dp"
        android:text="Your text" />

 </RelativeLayout>

And add onClickListener to the ImageView in your code.



来源:https://stackoverflow.com/questions/33650575/click-listener-for-drawableleft-in-edittext-in-android

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