I have added an image right of the text in an EditText
widget, using the following XML:
<EditText
android:id="@+id/txtsearch"
...
android:layout_gravity="center_vertical"
android:background="@layout/shape"
android:hint="Enter place,city,state"
android:drawableRight="@drawable/cross" />
But I want to clear the EditText
when the embedded image is clicked. How can I do this?
So many solutions, but none worked for me when I had two fields in a row. This is drop in solution for adding clear button to edit text, worked for me in my situations where I have two fields or one field in a row. Written in kotlin !
For anyone who does not want to implement the monstrous click handling. You can achieve the same with a
RelativeLayout
. With that you even have free handling of the positioning of the drawable.The
ImageView
position will be the same as you would usedrawableEnd
- plus you don't need all the touch listener handling. Just a click listener for theImageView
and you are good to go.I apply a short solution that is suitable even for fragments of dialogue.
and if drawable is on the left, this will help you. (for those work with RTL layout)
I've seen several solutions but I wasn't convinced by any of them. Either very complicated or too simple (non-reusable).
This is my favourite approach at the moment:
And this is the reusable touch listener:
You can look at the Gist here.
I implemented @aristo_sh answer in Mono.Droid (Xamarin), since it's a delegate anonymous method you can't return true or false you have to take take of e.Event.Handled. I am also hiding the keyboard on click