問題描述
在我的 Android 應用程序中,我需要實現一個 TextWatcher 接口來實現 onTextChanged
.我遇到的問題是,我想用一些額外的字符串更新相同的 EditText.當我嘗試這樣做時,程序會終止.
In my Android application I need to implement a TextWatcher interface to implement onTextChanged
. The problem I have is, I want to update the same EditText With some extra string. When I try to do this the program terminates.
final EditText ET = (EditText) findViewById(R.id.editText1);
ET.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
try
{
ET.setText("***"+ s.toString());
ET.setSelection(s.length());
}
catch(Exception e)
{
Log.v("State", e.getMessage());
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
@Override
public void afterTextChanged(Editable s)
{
}
});
我的程序終止了,即使我嘗試在我的代碼中捕獲異常,它仍然終止.有誰知道為什么會發生這種情況以及我如何做到這一點?謝謝.
My program terminates and even I try to catch the exception like in my code still it terminates. Does anyone have any idea why this happens and how I can achieve this? Thanks.
推薦答案
TextView
的內容在 onTextChanged
事件上不可編輯.
The content of the TextView
is uneditable on the onTextChanged
event.
相反,您需要處理 afterTextChanged
事件才能對文本進行更改.
Instead, you need to handle the afterTextChanged
event to be able to make changes to the text.
更詳盡的解釋參見:Android TextWatcher.afterTextChanged vs TextWatcher.onTextChanged
注意:錯誤onTextChanged
顯然,您正在通過不斷更改 afterTextChanged
事件上的 text 導致無限循環.
Obvioulsy, you are causing an endless loop by continuously changing the text on afterTextChanged
event.
來自 參考一個>:
public abstract void afterTextChanged (Editable s)
調用此方法是為了通知您,在 s 中的某處,文本已被改變了.從此對 s 進行進一步更改是合法的回調,但注意不要讓自己陷入無限循環,因為您所做的任何更改都會導致再次調用此方法遞歸地....
建議1:如果可以的話,檢查
s
是否已經在事件觸發時是你想要的.Suggestion 1: if you can, check if the
s
is already what you want when the event is triggered.@Override public void afterTextChanged(Editable s) { if( !s.equalsIngoreCase("smth defined previously")) s = "smth defined previously"; }
- 建議 2:如果您需要做更復雜的事情(格式化、驗證)您可以使用 synchronized 方法-textwatcher">這個發帖.
- Suggestion 2: if you need to do more complex stuff (formatting,
validation) you can maybe use a
synchronized
method like in this post.
注意 2:將輸入格式化為部分隱藏,并用 n 個星號直到最后一個 4 個字符(****四個)
Note 2 : Formatting the input as partially hidden with n stars till the last 4 chars ( ****four)
您可以在建議 1 中使用類似的內容:
You can use something like this in suggestion 1:
@Override
public void afterTextChanged(Editable s)
{
String sText = ET.getText().toString()
if( !isFormatted(sText))
s = format(sText);
}
bool isFormatted(String s)
{
//check if s is already formatted
}
string format(String s)
{
//format s & return
}
這篇關于如何使用 TextWatcher 更新相同的 EditText?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!