Date: 2020jul25
OS: Android
Language: Java
Q. Android: clear button beside EditText [X]
A. Add drawableRight to the resource
<EditText
...
android:drawableRight="@android:drawable/ic_menu_close_clear_cancel" />
There is no specific event, you need to listen for touches
mMyEditText.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
EditText et = (EditText) v;
final int DRAWABLE_LEFT = 0;
final int DRAWABLE_TOP = 1;
final int DRAWABLE_RIGHT = 2;
final int DRAWABLE_BOTTOM = 3;
if (event.getAction() == MotionEvent.ACTION_DOWN) {
final int closeIconWidth = et.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width();
if (event.getX() >= (et.getRight() - closeIconWidth)) {
// Do whatever you want
et.setText(""); // For example
return true;
}
}
return false;
}
});