如何使用TextWatcher更新相同的EditText? [英] How to update the same EditText using TextWatcher?
问题描述
在我的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
For more thorough explanation see: Android TextWatcher.afterTextChanged vs TextWatcher.onTextChanged
注意:错误 onTextChanged
很明显,通过不断更改<$ c $上的文本,您将导致无限循环c> afterTextChanged event。
Obvioulsy, you are causing an endless loop by continuously changing the text on afterTextChanged
event.
来自参考:
public abstract void afterTextChanged(Editable s)
调用此方法通知您,在s中的某个地方,文本已经是
cha nged。从
回调中对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 :如果您需要做更多复杂的东西(格式化,
验证)你可以使用<$ href =https://stackoverflow.com/questions/7435661/中的synchronized
方法edittext-not-updated-after-text-changed-in-the 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!