gpt4 book ai didi

android - afterTextChanged() 中的 setText() 以倒序显示文本

转载 作者:可可西里 更新时间:2023-11-01 11:42:19 25 4
gpt4 key购买 nike

我的代码:

    fractionNumEt.addTextChangedListener(new TextWatcher() {

boolean ignoreChange = false;

@Override
public void afterTextChanged(Editable s) {
if(!ignoreChange) {
String string = String.valueOf(s);
if (string.length() > 2) {
string = string.substring(0, string.length() - 1);
ignoreChange = true;
fractionNumEt.setText(string);
ignoreChange = false;
}
}

}

....

我正在尝试将字符长度限制为 2,但想继续收听。当我键入“1”、“2”时,它会显示“12”,这很好。现在,当我输入“3”时,它会显示“31”而不是“23”。这到底是怎么回事!我也试过:

string = string.substring(1, string.length());

在这种情况下,它第一次只工作 n 然后什么都没有改变。

最佳答案

发生这种情况是因为在 setText() 之后,EditText 的光标返回到第一个位置。然后,任何新数字都将添加到字符串的开头。

尝试按如下方式更新您的代码:

@Override
public void afterTextChanged(Editable s) {
if(!ignoreChange) {
String string = String.valueOf(s);
if (string.length() > 2) {
string = string.substring(0, string.length() - 1);
ignoreChange = true;
fractionNumEt.setText(string);
fractionNumEt.setSelection(fractionNumEt.getText().length());
ignoreChange = false;
}
}
}

只是一个建议

检查可编辑文档 HERE

我认为您不需要将其转换为字符串。 afterTextChanged(Editable s) 接收一个 Editable 作为参数。您可以直接更改它。不需要将其转换为字符串。

此外:您甚至不需要制作 EditText.setText() 因为可编辑的任何更改都会自动传递给 EditText(因为 afterTextChanged 由 android 调用并给您机会在几分钟前更新文本以有效地在 EditText 中显示该文本)。

也许,像那样:

@Override
public void afterTextChanged(Editable s) {
if(!ignoreChange) {
if(s.length() > 2) {
s.delete(s.length() - 1,s.length());
}
}
}

稍微玩一下 Editable,您会发现它更容易。

关于android - afterTextChanged() 中的 setText() 以倒序显示文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35771768/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com