问题
I have edittext and want to add to right "search" icon..
searchTxt.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.search, 0);
But how can I add event for click 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;
}
}
});
??
回答1:
Drawables are non-interactive elements, so you cannont set a click listener on a drawable.
A simple solution would be putting an ImageView
containing the "search" icon over the EditText
and adding a right padding on the EditText
so the text doesn't 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>
回答2:
you need to connect your listener with the resource id of your button or image.
actually you can make an image into a button. or just replace the button with your image. you add a selector in 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 your 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 tie the image in source with the button id
回答3:
well i would suggest instead of doing all these you can just add alignLeft,alignTop,alignBottom,alignTop tags into the image view you are using 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 id of the edittext
来源:https://stackoverflow.com/questions/20724287/how-can-i-add-onclicklistener-to-drawable-in-edittext