問題描述
我對 TextWatcher
了解一些,但它會在您輸入的每個字符上觸發.我想要一個在用戶完成編輯時觸發的監聽器.是否可以?同樣在 TextWatcher
中,我得到了一個 Editable
的實例,但我需要一個 EditText
的實例.我怎么得到它?
I know a little bit about TextWatcher
but that fires on every character you enter. I want a listener that fires whenever the user finishes editing. Is it possible? Also in TextWatcher
I get an instance of Editable
but I need an instance of EditText
. How do I get that?
EDIT:第二個問題更重要.請回答.
EDIT: the second question is more important. Please answer that.
推薦答案
首先,如果 EditText
失去焦點或用戶按下完成按鈕(這取決于您的實施以及最適合您的方式).其次,只有將 EditText
聲明為實例對象,才能在 TextWatcher
中獲取 EditText
實例.即使您不應該在 TextWatcher
中編輯 EditText
,因為它不安全.
First, you can see if the user finished editing the text if the EditText
loses focus or if the user presses the done button (this depends on your implementation and on what fits the best for you).
Second, you can't get an EditText
instance within the TextWatcher
only if you have declared the EditText
as an instance object. Even though you shouldn't edit the EditText
within the TextWatcher
because it is not safe.
為了能夠將 EditText
實例放入您的 TextWatcher
實現中,您應該嘗試這樣的操作:
To be able to get the EditText
instance into your TextWatcher
implementation, you should try something like this:
public class YourClass extends Activity {
private EditText yourEditText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
yourEditText = (EditText) findViewById(R.id.yourEditTextId);
yourEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// you can call or do what you want with your EditText here
// yourEditText...
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
}
}
請注意,上面的示例可能有一些錯誤,但我只是想向您展示一個示例.
Note that the above sample might have some errors but I just wanted to show you an example.
這篇關于android edittext onchange 監聽器的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!