[英]How to implement TextWatcher interface on Edit Text with Xamarin Android?
我正在嘗試實現一個接口,當用戶在其上鍵入單個字符時,它將在我的EditText
上偵聽,這樣當發生這種情況時,我將收到一條 Toast 消息,提示You tried to type a new character
,並且當用戶清除時,此接口將檢查EditText
中字符的長度,並顯示一條 Toast 消息,如果count
為 0,則清除所有文本。這就是Android.Text.IWatcher
接口的用武之地。我已經在我的主要 class 中實現了它,就像這樣......
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,請幫我解決這個問題,謝謝。
為什么不直接使用在EditText
上公開的 C# 事件呢?
user_message.TextChanged += OnTextChanged;
然后實現方法:
private void OnTextChanged(object sender, TextChangedEventArgs e)
{
if (e.Text.Count() > 0)
{
// do stuff
}
}
創建一個 TextWatcher class,然后將此偵聽器添加到 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());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.