Home > database >  How to implement TextWatcher interface on Edit Text with Xamarin Android?
How to implement TextWatcher interface on Edit Text with Xamarin Android?

Time:12-06

I am trying to implement an interface that will listen on my EditText when user types a single character on it such that when that happens I will get a Toast message that You tried to type a new character and when user clears then this interface will check the length of the characters inside the EditText and display a Toast message that you cleared all the text if the count is 0. This is where the Android.Text.IWatcher interface comes in. I have implemented it in my main class like this...

public class MainActivity : AppCompatActivity,ITextWatcher
    {
      //after I implemented the interface then these methods were generated by the compiler
       public void OnTextChanged(Java.Lang.ICharSequence s, int start, int before, int count)
        {
           //check the length of characters typed and show a Toast
            if (s.Length() > 0)
            {
                
                Toast.MakeText(this, "You are typing more text", ToastLength.Long).Show();
            }
     //if user clears all text also show a Toast
            if (s.Length() == 0)
            {
               
                Toast.MakeText(this, "You have cleared all the text", ToastLength.Long).Show();
            }
        }
    }

I assigned the Interface to my EditText like below.

               EditText user_message = chat_view.FindViewById<EditText>(Resource.Id.message_box);
                //assign a text watcher to the EditText
               user_message.AddTextChangedListener(this);

The problem is that I do not get the Toasts when I type in my EditText when i debug this application to my android device, help me resolve this, Thank You.

CodePudding user response:

Why don't you just use the C# event exposed on the EditText instead?

user_message.TextChanged  = OnTextChanged;

Then implement the method:

private void OnTextChanged(object sender, TextChangedEventArgs e)
{
    if (e.Text.Count() > 0)
    {
        // do stuff
    }
}

CodePudding user response:

Create a TextWatcher class and then add this listener to the EditText.

 public class TextWatcher : Java.Lang.Object, ITextWatcher
{
    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)
    {
        Console.WriteLine("---------------------------"   s);
    }
}

Usage:

SetContentView(Resource.Layout.layout4);
        var editText = FindViewById<EditText>(Resource.Id.editText1);
        editText.AddTextChangedListener(new TextWatcher());
  • Related