Skip to content

Instantly share code, notes, and snippets.

@justintoth
Created February 21, 2018 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justintoth/9562c13b3d1d5e57571b4d4ed999907b to your computer and use it in GitHub Desktop.
Save justintoth/9562c13b3d1d5e57571b4d4ed999907b to your computer and use it in GitHub Desktop.
Custom edit text control with clear button for Xamarin Android
public class CustomEditText : EditText {
private Drawable clearButton;
protected CustomEditText (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {
}
public CustomEditText (Context context) : base (context) {
Init ();
}
public CustomEditText (Context context, IAttributeSet attrs) : base (context, attrs) {
Init (attrs);
}
public CustomEditText (Context context, IAttributeSet attrs, int defStyle) : base (context, attrs, defStyle) {
Init (attrs);
}
private void Init (IAttributeSet attrs = null) {
var activity = ApplicationContext.Activity;
if (activity == null)
return;
clearButton = ContextCompat.GetDrawable (Android.App.Application.Context, Resource.Drawable.forms_edit_text_clear_gray);
clearButton.SetBounds (0, 0, clearButton.IntrinsicWidth, clearButton.IntrinsicHeight);
SetupEvents ();
}
private void SetupEvents () {
// Handle clear button visibility
this.TextChanged += (sender, e) => {
UpdateClearButton ();
};
this.FocusChange += (sender, e) => {
UpdateClearButton (e.HasFocus);
};
// Handle clearing the text
this.Touch += (sender, e) => {
if (this.GetCompoundDrawables ()[2] == null || e.Event.Action != MotionEventActions.Up) {
e.Handled = false;
return;
}
if (e.Event.GetX () > (this.Width - this.PaddingRight - clearButton.IntrinsicWidth)) {
this.Text = "";
UpdateClearButton ();
e.Handled = true;
} else
e.Handled = false;
};
}
private void UpdateClearButton (bool hasFocus = true) {
var compoundDrawables = this.GetCompoundDrawables ();
var compoundDrawable = this.Text.Length == 0 || !hasFocus ? null : clearButton;
this.SetCompoundDrawables (compoundDrawables[0], compoundDrawables[1], compoundDrawable, compoundDrawables[3]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment