Skip to content

Instantly share code, notes, and snippets.

@felipeslongo
Last active April 23, 2019 16:22
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 felipeslongo/42bb608c6c1c5d3654c897a661603a54 to your computer and use it in GitHub Desktop.
Save felipeslongo/42bb608c6c1c5d3654c897a661603a54 to your computer and use it in GitHub Desktop.
Setup a clear icon that when clicked executes que action provided
using System;
using Android.Text;
using Android.Views;
using Android.Widget;
using App.Droid.Utils;
namespace App.Droid.Extensions
{
/// <summary>
///
/// </summary>
/// <seealso cref="https://stackoverflow.com/questions/6355096/how-to-create-edittext-with-crossx-button-at-end-of-it"/>
/// <seealso cref="https://stackoverflow.com/questions/3554377/handling-click-events-on-a-drawable-within-an-edittext"/>
/// <seealso cref="https://stackoverflow.com/questions/13135447/setting-onclicklistener-for-the-drawable-right-of-an-edittext?noredirect=1&lq=1"/>
public static class EditText_SetupClearButtonWithAction
{
public static void SetupClearButtonWithAction(this EditText @this, Action clearAction)
{
@this.AfterTextChanged += SetupIconBasedOnTextLenght;
@this.FocusChange += SetupIconBasedOnTextLenght;
SetupClearActionOnIconClick(@this, clearAction);
}
private static void SetupIconBasedOnTextLenght(object sender, View.FocusChangeEventArgs e) =>
DefinirIconeSeBaseandoNaPresencaDeTexto((EditText)sender, !string.IsNullOrEmpty((sender as EditText).Text));
private static void SetupIconBasedOnTextLenght(object sender, AfterTextChangedEventArgs args) =>
DefinirIconeSeBaseandoNaPresencaDeTexto((EditText)sender,args.Editable.Length() > 0);
private static void SetupIconBasedOnTextLenght(EditText @this, bool textoPreenchido)
{
var clearIcon = textoPreenchido && @this.HasFocus ? Resource.Drawable.ic_content_clear : 0;
@this.SetCompoundDrawablesWithIntrinsicBounds(0, 0, clearIcon, 0);
}
private static void SetupClearActionOnIconClick(EditText view, Action clearAction) =>
TextViewDrawableTouchEventHandler.SetupRightDrawableClick(view, clearAction);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment