It is very common that the Android's Edit text needs to clear all filled data in one hit, rather than clearing every single text using keyboard's 'X' button.
It is a good practice that enable user to clear all the text using Edit Text drawable.
public class ClearEdit extends AppCompatAutoCompleteTextView implements View.OnTouchListener, View.OnFocusChangeListener, TextWatcher {
private Drawable clrIcon;
private OnFocusChangeListener mOnFocusChangeListener;
private OnTouchListener mOnTouchListener;
public ClearEdit(final Context context) {
super(context);
init(context);
}
public ClearEdit(final Context context, final AttributeSet attrs) {
super(context, attrs);
init(context);
}
public ClearEdit(final Context context, final AttributeSet attrs, final int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
@Override
public void setOnFocusChangeListener(OnFocusChangeListener onFocusChangeListener) {
mOnFocusChangeListener = onFocusChangeListener;
}
@Override
public void setOnTouchListener(OnTouchListener onTouchListener) {
mOnTouchListener = onTouchListener;
}
private void setClearIconVisible(final boolean visible) {
clrIcon.setVisible(visible, false);
final Drawable[] compoundDrawables = getCompoundDrawables();
setCompoundDrawables(
compoundDrawables[0],
compoundDrawables[1],
visible ? clrIcon : null,
compoundDrawables[3]);
}
private void init(final Context context) {
// add your drawable here
final Drawable drawable = ContextCompat.getDrawable(context, R.drawable.abc_ic_clear_mtrl_alpha);
final Drawable wrappedDrawable = DrawableCompat.wrap(drawable); //Wrap the drawable so that it can be tinted pre Lollipop
DrawableCompat.setTint(wrappedDrawable, getCurrentHintTextColor());
clrIcon = wrappedDrawable;
clrIcon.setBounds(0, 0, clrIcon.getIntrinsicHeight(), clrIcon.getIntrinsicHeight());
setClearIconVisible(false);
super.setOnTouchListener(this);
super.setOnFocusChangeListener(this);
addTextChangedListener(this);
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
setClearIconVisible(getText().length() > 0);
} else {
setClearIconVisible(false);
}
if (mOnFocusChangeListener != null) {
mOnFocusChangeListener.onFocusChange(v, hasFocus);
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
final int x = (int) event.getX();
if (clrIcon.isVisible() && x > getWidth() - getPaddingRight() - clrIcon.getIntrinsicWidth()) {
if (event.getAction() == MotionEvent.ACTION_UP) {
setText("");
}
return true;
}
return mOnTouchListener != null && mOnTouchListener.onTouch(v, event);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
if (isFocused()) {
setClearIconVisible(text.length() > 0);
}
}
}
0 Comment(s)