問(wèn)題描述
在我的 Android 應(yīng)用程序中,我需要實(shí)現(xiàn)一個(gè) TextWatcher 接口來(lái)實(shí)現(xiàn) onTextChanged
.我遇到的問(wèn)題是,我想用一些額外的字符串更新相同的 EditText.當(dāng)我嘗試這樣做時(shí),程序會(huì)終止.
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)
{
}
});
我的程序終止了,即使我嘗試在我的代碼中捕獲異常,它仍然終止.有誰(shuí)知道為什么會(huì)發(fā)生這種情況以及我如何做到這一點(diǎn)?謝謝.
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
的內(nèi)容在 onTextChanged
事件上不可編輯.
The content of the TextView
is uneditable on the onTextChanged
event.
相反,您需要處理 afterTextChanged
事件才能對(duì)文本進(jìn)行更改.
Instead, you need to handle the afterTextChanged
event to be able to make changes to the text.
更詳盡的解釋參見(jiàn):Android TextWatcher.afterTextChanged vs TextWatcher.onTextChanged
注意:錯(cuò)誤onTextChanged
顯然,您正在通過(guò)不斷更改 afterTextChanged
事件上的 text 導(dǎo)致無(wú)限循環(huán).
Obvioulsy, you are causing an endless loop by continuously changing the text on afterTextChanged
event.
來(lái)自 參考一個(gè)>:
public abstract void afterTextChanged (Editable s)
調(diào)用此方法是為了通知您,在 s 中的某處,文本已被改變了.從此對(duì) s 進(jìn)行進(jìn)一步更改是合法的回調(diào),但注意不要讓自己陷入無(wú)限循環(huán),因?yàn)槟龅娜魏胃亩紩?huì)導(dǎo)致再次調(diào)用此方法遞歸地....
建議1:如果可以的話,檢查
s
是否已經(jīng)在事件觸發(fā)時(shí)是你想要的.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:如果您需要做更復(fù)雜的事情(格式化、驗(yàn)證)您可以使用 synchronized 方法-textwatcher">這個(gè)發(fā)帖.
- 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 個(gè)星號(hào)直到最后一個(gè) 4 個(gè)字符(****四個(gè))
Note 2 : Formatting the input as partially hidden with n stars till the last 4 chars ( ****four)
您可以在建議 1 中使用類似的內(nèi)容:
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
}
這篇關(guān)于如何使用 TextWatcher 更新相同的 EditText?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!