【问题标题】:How to implement TextWatcher interface on Edit Text with Xamarin Android?如何使用 Xamarin Android 在 Edit Text 上实现 TextWatcher 接口?
【发布时间】:2022-01-10 10:22:18
【问题描述】:

我正在尝试实现一个接口,当用户在其上键入单个字符时,该接口将在我的EditText 上进行侦听,这样当发生这种情况时,我将收到一条 Toast 消息,You tried to type a new character 并且当用户清除时,此接口将检查EditText 中的字符长度,并显示一个 Toast 消息,如果 count 为 0,则清除所有文本。这就是 Android.Text.IWatcher 接口的用武之地。我已经在我的主类中实现了它,如下所示...

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();
            }
        }
    }

我将接口分配给我的EditText,如下所示。

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

问题是当我在我的 Android 设备上调试这个应用程序时输入我的 EditText 时没有得到 Toasts,请帮我解决这个问题,谢谢。

【问题讨论】:

    标签: c# android xamarin textwatcher


    【解决方案1】:

    为什么不直接使用EditText 上公开的 C# 事件呢?

    user_message.TextChanged += OnTextChanged;
    

    然后实现方法:

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

    【讨论】:

    • 我会按照你的建议尝试实施,看看我是否会得到一些结果并将其标记为已接受,@Cheesebaron
    • 视图被夸大了,正在使用当前的活动类来调用 Toast,这可能是原因吗?
    • 使用您的调试器并缩小正在发生的事情。我无法重现您的问题...
    • 好的,我必须启动一个新的 Activity Intent 来处理编辑文本事件,谢谢您的帮助
    【解决方案2】:

    创建一个 TextWatcher 类,然后将此侦听器添加到 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);
        }
    }
    

    用法:

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

    【讨论】:

    • 已经找到解决方法,但感谢您的回答
    • 很高兴为您提供帮助。希望这种方式对您的问题有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多