This method is universal, not only for EditText, but also for TextView, Autocompletetextview and other controls.
Google's official API does not give a direct way to set the right image of the Click event, so here we need to click on the location to determine the click of the event, the effect is as shown:
Layout file:
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"
xmlns:tools= "http:// Schemas.android.com/tools "
android:layout_width=" match_parent "
android:layout_height=" Match_parent "
android:paddingbottom= "@dimen/activity_vertical_margin"
android:paddingleft= "@dimen/activity_ Horizontal_margin "
android:paddingright=" @dimen/activity_horizontal_margin "
android:paddingtop=" @dimen /activity_vertical_margin "
tools:context=" com.example.drablerighttest.MainActivity ">
<edittext
android:id= "@+id/et"
android:layout_width= "350DP"
android:layout_height= "Wrap_content"
android:drawableright= "@drawable/search_clear_pressed"
android:text= "@string/hello_world"/>
</ Relativelayout>
Mainactivity.java
public class Mainactivity extends activity {
private edittext et;
@Override
protected void onCreate (Bundle savedinstancestate) {
super.oncreate (savedinstancestate);
Setcontentview (r.layout.activity_main);
ET = (edittext) This.findviewbyid (r.id.et);
Et.setontouchlistener (New Ontouchlistener () {
@Override public
boolean Ontouch (View V, motionevent event) {
//Et.getcompounddrawables () gets an array of length 4, representing the left and right four pictures
respectively drawable drawable = Et.getcompounddrawables () [2];
If there is no picture on the right, no longer process
if (drawable = null) return
false;
If the event is not pressed, the
if (event.getaction ()!= motionevent.action_up) return false is no longer processed
;
if (Event.getx () > Et.getwidth ()
-et.getpaddingright ()
-drawable.getintrinsicwidth ()) {
Et.settext ("");
}
return false;}}
);
}
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.