gpt4 book ai didi

java - Android EditText 符号必须保持在初始位置

转载 作者:行者123 更新时间:2023-12-01 11:27:16 25 4
gpt4 key购买 nike

我有一个文本字段,其起始符号为 $(可能是欧元或英镑,具体取决于应用程序设置)。我需要这样做,以便如果用户在符号之前单击,则不会发生任何事情。换句话说,选择必须保留在符号之后。我尝试做这样的事情,但它似乎是错误的,它给了我一个错误:

billAmount.addTextChangedListener(new TextWatcher() {

//other methods

@Override
public void afterTextChanged(Editable s) {
billAmount.setText(currencySymbol + billAmount.getText().toString());
}
});

我正在考虑使用 inputFilter 但我尝试的任何方法都不起作用。我也不允许在 EditText 之前使用 TextView。

最佳答案

首先,在您的代码示例中,您收到错误的原因是,正如其他人所说,您在 afterTextChanged 方法内调用 setText 方法。调用 setText 显然会更改文本,从而导致 afterTextChanged 再次被调用。这会导致 afterTextChanged 被连续调用,直到最终出现堆栈溢出。

您有两个问题:1) 您希望始终将光标定位在货币符号之后,2) 您希望确保货币符号永远不会以某种方式被删除。

解决第一个问题的最简单方法是创建 EditText 的子类并重写 onSelectionChanged 方法。

public class MyEditText extends EditText {

// ...

@Override
public void onSelectionChanged(int selStart, int selEnd) {
super.onSelectionChanged(selStart, selEnd);

// Make sure the text's length is greater than zero.
// Then, if the cursor is at position zero...
if (getText().length() > 0 && selStart == 0) {
// ...move it over to position one.
setSelection(1, selEnd);
}
}
}

这将强制光标始终位于货币符号之后,即使用户尝试将其移动到货币符号之前也是如此。检查 getText().length() > 0 是为了确保 EditText 至少包含一个字符,否则尝试移动光标将导致异常。

对于#2,有几种方法可以实现。您可以尝试在 TextWatcher 中使用一些实例变量来跟踪文本何时​​需要格式化,但这不会阻止实际发生不必要的方法调用,并且会增加一些不必要的复杂性。我认为简单地使用 InputFilter 会更容易,您可以在扩展 EditText 的构造函数中指定它。

public class MyEditText extends EditText {

public MyEditText(Context context) {
super(context);

// Set the EditText's input filter.
setFilters(new InputFilter[] { new InputFilter {
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
// If the currency symbol is about to be replaced...
if (dstart == 0)
// Add the currency symbol to the front of the source.
return currencySymbol + source;
// else
// Return null to indicate that the change is okay.
return null;
}
}});
}

// ...
}

filter 方法中,dest 参数表示 EditText 的文本,dstartdend 参数表示要替换的文本部分的开始和结束位置。由于货币符号应始终是第一个字符,因此如果 dstart 为零,我们就知道它将被替换,在这种情况下,我们只需返回源(代表替换文本),货币符号放在前面。否则,我们通过返回 null 来表明更改是可以的。

我测试了它,它似乎可以满足您的需要。

顺便说一句,虽然我知道您不“被允许”使用 TextView,但我认为值得重申的是,使用 TextView 将为该问题提供更好的解决方案。一种特别有用的解决方案是让隐藏的 EditText 包含来自用户的原始输入,并将 TextView 放在 EditText 之上。您可以使用 TextWatcher 使用 EditText 中格式正确的输入来更新 TextView

关于java - Android EditText 符号必须保持在初始位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30722197/

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