dro*_*bee 5 android textwatcher android-edittext
我正在使用TextWatcher来监听按键输入。当用户键入“ @”时,我打开一个listactivity,用户必须从列表中进行选择。选择之后,我将所选项目的文本(包括首字母@)放置到edittext中,然后继续进行正常的编辑。
问题是,当我按退格键时,在aftertextchanged事件中得到的字符串是错误的,并且再次弹出listactivity。
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
@Override
public void afterTextChanged(Editable s)
{
String str = s.toString();
if (str.length() > 0)
{
if (str.substring(str.length() - 1).equals("@"))
{
Intent i = new Intent(MessageComposeActivity.this, MembersListActivity.class);
startActivityForResult(i, Util.MEMBERS_LIST);
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
并在onActivityResult中:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Util.MEMBERS_LIST)
if (resultCode == RESULT_OK)
{
editText.setText(editText.getText().toString() + data.getExtras().get("screenname") + " ");
editText.setSelection(editText.getText().length());
}
}
Run Code Online (Sandbox Code Playgroud)
例如:
在EditText中,键入“ @”,然后弹出活动,然后选择“ James”。EditText现在显示@James。如果我按退格键一次或两次,则在编辑文本显示@Jam时,listactivity再次弹出。
PS:afterTextChanged()有时会为退格键(或任何键)调用两次,在afterTextChanged()的第二次执行时,我得到了错误的输入字符串。第一次执行afterTextChanged()时,我得到@Jam,而在第二次执行时,我得到'@',因此会弹出listactivity。
问题: 为什么afterTextChanged()被调用两次,为什么在第二次执行时输入错误的文本?
非常感谢。
我有同样的问题。我不知道是什么导致了长度为 0 的可编辑/字符序列的额外错误回调。
我正在寻找对 EditText 的更改,实际上导致了一个空的 EditText。我最终不得不实现一个处理程序来检查 500 毫秒后的 EditText 长度。您可能必须使您的编辑文本静态或最终。它应该看起来像这样:
final Handler handler =new Handler();
final Runnable r = new Runnable(){
@Override
public void run()
{
//
String str = editText.getText().toString();
if (str.length() > 0)
{
if (str.substring(str.length() - 1).equals("@"))
{
Intent i = new Intent(MessageComposeActivity.this, MembersListActivity.class);
startActivityForResult(i, Util.MEMBERS_LIST);
}
}
}
} ;
editText.addTextChangedListener(new TextWatcher()
{
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3)
{
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3)
{
}
@Override
public void afterTextChanged(Editable s)
{
handler.postDelayed(r,500);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1713 次 |
| 最近记录: |