I have created an EditText
for search, which contains on the left side a search icon and on the right side of icon:
<EditText
android:id="@+id/Search"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:drawableLeft="@android:drawable/ic_menu_search"
android:drawableRight="@android:drawable/ic_delete"
android:hint="Search Product .." >
</EditText>
I want to know how can I clear the content of EditText
when I click the cross button.
Thank you in advance.
An improved answer by @aristo_sh from Handling click events on a drawable within an EditText
mQueryEditText.setOnTouchListener(new OnTouchListener() {
final int DRAWABLE_LEFT = 0;
final int DRAWABLE_TOP = 1;
final int DRAWABLE_RIGHT = 2;
final int DRAWABLE_BOTTOM = 3;
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
int leftEdgeOfRightDrawable = mQueryEditText.getRight()
- mQueryEditText.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width();
// when EditBox has padding, adjust leftEdge like
// leftEdgeOfRightDrawable -= getResources().getDimension(R.dimen.edittext_padding_left_right);
if (event.getRawX() >= leftEdgeOfRightDrawable) {
// clicked on clear icon
mQueryEditText.setText("");
return true;
}
}
return false;
}
});