Search code examples
androidxamarinonkeyup

Xamarin android format string onkey pressed


I have this EditText in which I want the user to type a credit card number, so I want to format the string while the user is typing it, I specifically want the string to have a space every 4 numbers, like this:

xxxx xxxx xxxx xxxx

I found that I could use TextWatcher and onKeyUp but I couldn't understand how use it in a EditText, if some one could explain me I would really appreciate it, thanks.


Solution

  • Create a class that implements the ITextWatcher interface. Then add an instance of that class as a text changed listener...

    public class CreditCardFormatter : Java.Lang.Object, ITextWatcher
    {
        private EditText _editText;
        public CreditCardFormatter(EditText editText)
        {
         _editText = editText;
        }
    
        public void AfterTextChanged(IEditable s)
        {
        }
    
        public void BeforeTextChanged(ICharSequence s, int start, int count, int after)
        {
        }
    
        public void OnTextChanged(ICharSequence s, int start, int before, int count)
        {
        }
    }
    

    In your activity.. (or OnCreateView in a fragment)

    public override void OnCreate()
    {
        // other code..
        myEditText.AddTextChangedListener(new CreditCardFormatter(myEditText));
    }
    

    Then use the override methods to reformat the text to show what you need.