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?
Simply copy paste the following code and it does the trick.
for left drawable click listener
Sharing my generalized solution for handling TextView compound drawable click and touch events.
First we need a touch event handler:
Now you can process any touch events on any compound drawable of any TextView you like this way:
Only interested in clicks? Just filter out by MotionEvent action:
Again we can easily handle clicks on any compound drawable of any TextView:
Hope you liked it as I did. I will try to keep it updated here and in related gist if anything changes.
Consider the following. It's not the most elegant solution but it works, I just tested it.
Create a customized
EditText
classCustomEditText.java
:Change your layout XML to this (where
com.example
is your actual project package name):Finally, add this (or something similar) to your activity:
I might be a bit off with the calculation of the touch bounds for the nested drawable but you get the idea.
I hope this helps.
Extending on the idea by RyanM I have created a more flexible version, which supports all the drawable types (top, bottom, left, right). While the code below extends TextView, adapting it for an EditText is just a case of swapping "extends TextView" with "extends EditText". Instantiation the widget from XML is identical as in RyanM's example, bar the widget name.
The DrawableClickListener is as simple as this:
And then the actual implementation:
p.s.: If you don't set the listener, touching the TextView will cause a NullPointerException. You may want to add some more paranoia into the code.
Very, very good, thanks to everyone who contributed to this discussion. So if you don't want to deal with inconvenience of extending the class you can do the following (implemented for the right drawable only)
And here's bare-bone listener implementation based on @Mark's answer