How can I add OnClickListener to Drawable in EditText?

I have an edittext and you want to add a search icon to the desired icon.

searchTxt.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.search, 0); 

But how can I add an event for this icon?

 searchTxt.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { Drawable co = ((TextView) v).getCompoundDrawables()[2]; if (event.getX() > v.getMeasuredWidth() - v.getPaddingRight() - co.getIntrinsicWidth()) { Datas.search = searchTxt.getText().toString(); startActivity(Search.class); return true; } else { return false; } } }); 

??

+6
source share
3 answers

Drawables are non-interactive elements, so you cannot set the click listener to drawable. A simple solution would be to put an ImageView containing the search icon above the EditText and add the correct addition to the EditText so that the text does not overlap with the icon.

 <FrameLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <EditText ... android:paddingRight="..." ... /> <ImageView ... android:src="@drawable/search" android:layout_gravity="right|center_vertical" ... /> </FrameLayout> 
+7
source

you need to connect a listener with the resource identifier of your button or image.

in fact, you can make the image as a button. or just replace the button with your image. you add a selector to res / drawable.

 <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android" > <item android:state_enabled="false" android:drawable="@drawable/yourImage" /> <item android:state_pressed="true" android:state_enabled="true" android:drawable="@drawable/yourImagePressed" /> <item android:state_focused="true" android:state_enabled="true" android:drawable="@drawable/yourImagePressed" /> <item android:state_enabled="true" android:drawable="@drawable/yourImage" /> 

then add to the layout

 <Button android:id="@+id/yourButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="18sp" android:background="@drawable/button_background_selector" android:text="@string/yourStr" android:textColor="#ffffffff" /> 

you would then associate the image in the source with the button id

0
source

Well, I would suggest instead of doing all this, you can just add labels alignLeft, alignTop, alignBottom, alignTop to the image you use, like this

 <ImageView android:id="@+id/img_view_search" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@id/edt_text_search" android:layout_alignRight="@id/edt_text_search" android:layout_alignTop="@id/edt_text_search" android:src="@drawable/search_selected" android:padding="2dp" /> 

edt_text_search is the edittext identifier

0
source

All Articles