Skip to content

Instantly share code, notes, and snippets.

@polbins
Created December 27, 2016 03:21
Show Gist options
  • Save polbins/e97850516250f1fb896cf7029927680c to your computer and use it in GitHub Desktop.
Save polbins/e97850516250f1fb896cf7029927680c to your computer and use it in GitHub Desktop.
Clearable EditText Custom View

Clearable EditText Custom View

EditText with an ic_clear drawable on the right for instantly deleting text

public class ClearableEditText extends EditText {
@BindDrawable(R.drawable.ic_clear_dark_gray)
Drawable mClearDrawable;
public ClearableEditText(Context context) {
super(context);
init();
}
public ClearableEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
ButterKnife.bind(this);
// Right Drawable onClick Listener
setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
final int DRAWABLE_RIGHT = 2;
if (event.getAction() == MotionEvent.ACTION_UP &&
getCompoundDrawables()[DRAWABLE_RIGHT] != null) {
if (event.getRawX() >= (getRight() -
getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
// Clear the Text when Right Drawable is Clicked
setText("");
return true;
}
}
return false;
}
});
}
@Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
super.onTextChanged(text, start, lengthBefore, lengthAfter);
if (TextUtils.isEmpty(text)) {
// Remove Clear Drawable when Text is Empty
setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
} else {
// Add Clear Drawable when there is some Text
setCompoundDrawablesWithIntrinsicBounds(null, null, mClearDrawable, null);
}
}
}
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#FF777777"
android:pathData="M19,6.41L17.59,5 12,10.59 6.41,5 5,6.41 10.59,12 5,17.59 6.41,19 12,13.41 17.59,19 19,17.59 13.41,12z"/>
</vector>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment