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?
Better to have ImageButton on Right of edit text and give negative layout margin to overlap with edit text. Set listener on ImageButton and perform operations.
Its very simple. Lets say you have a drawable on left side of your EditText 'txtsearch'. Following will do the trick.
If you want for right drawable change the if statement to:
Similarly, you can do it for all compound drawables.
This method call returns all the padding on that side including any drawables. You can use this even for TextView, Button etc.
Click here for reference from android developer site.
Actually you don't need to extend any class. Let's say I have an EditText editComment with a drawableRight
we
getRawX()
because we want to get the actual position of touch on screen, not relative to parent.To get left side click
That last contribution's use of
contains(x,y)
won't work directly on the result ofgetBounds()
(except, by coincidence, when using "left" drawables). ThegetBounds
method only provides theRect
defining points of the drawable item normalized with origin at 0,0 - so, you actually need to do the math of the original post to find out if the click is in the area of the drawable in the context of the containing EditText's dimensions, but change it for top, right, left etc. Alternatively you could describe aRect
that has coordinates actually relative to its position in theEditText
container and usecontains()
, although in the end you're doing the same math.Combining them both gives you a pretty complete solution, I only added an instance attribute
consumesEvent
that lets the API user decide if the click event should be passed on or not by using its result to setACTION_CANCEL
or not.Also, I can't see why the
bounds
andactionX
,actionY
values are instance attributes rather than just local on the stack.Here's a cutout from an implementation based on the above that I put together. It fixes an issue that to properly consume the event you need to return false. It adds a "fuzz" factor to. In my use case of a Voice control icon in an
EditText
field, I found it hard to click, so the fuzz increases the effective bounds that are considered clicking the drawable. For me15
worked well. I only neededdrawableRight
so I didn't plug the math in the others, to save some space, but you see the idea.