我在输入EditText时正在使用TextWatcher编辑值
这是我的TextWatcher
public class NumberTextWatcher implements TextWatcher {
private DecimalFormat df;
private DecimalFormat dfnd;
private boolean hasFractionalPart;
private EditText et;
public NumberTextWatcher(EditText et)
{
df = new DecimalFormat("#,###");
df.setDecimalSeparatorAlwaysShown(true);
dfnd = new DecimalFormat("#,###");
this.et = et;
hasFractionalPart = false;
}
@SuppressWarnings("unused")
private static final String TAG = "NumberTextWatcher";
@Override
public void afterTextChanged(Editable s)
{
et.removeTextChangedListener(this);
try {
int inilen, endlen;
inilen = et.getText().length();
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
Number n = df.parse(v);
int cp = et.getSelectionStart();
if (hasFractionalPart) {
et.setText(df.format(n));
} else {
et.setText(dfnd.format(n));
}
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel <= et.getText().length()) {
et.setSelection(sel);
} else {
// place cursor at the end?
et.setSelection(et.getText().length() - 1);
}
} catch (NumberFormatException nfe) {
// do nothing?
} catch (ParseException e) {
// do nothing?
}
et.addTextChangedListener(this);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator())))
{
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
}
之后,我尝试使用以下代码将值解析为双精度:
String amount1 = amount.getText().toString().replaceAll("[^\\d]", "");
String duration1 = duration.getText().toString().replaceAll("[^\\d]", "");
String interest1 = interest.getText().toString().replaceAll("[^\\d]", "");
但是我的问题是,当“设备默认语言”不是英语时,它可以将字符串解析为Doubles,因此我认为我为editTexts设置了美国语言环境!这可能吗?如果没有,我应该怎么做才能将值解析为两倍?
DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.US);
最佳答案
当您控制了后端时,我发现最容易处理所需的语言并进行了广泛的测试。因此,当处理我内部具有的文件的文件IO时,在执行任何文件创建代码之前,我总是在注释末尾调用您拥有的调用。就我而言
final DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getInstance(Locale.ENGLISH); //Format our data to two decimal places for brightness change.
String stringFormat = "#0.00";
decimalFormat.applyPattern(stringFormat);
decimalFormat.format(dataString);
然后,无论设备实际设置为哪种语言,您都将使用自己习惯的语言环境。这将有助于处理其他可能使用不同数字格式的语言,例如在这种情况下,因为我正在处理数字。由于您要处理双打,因此您可能正在解决此数字转换问题。但是,如果您要处理EditText的输入,则仅适用于后端的这种特定方法可能不适用。但是我认为交流我的方法可能还是有帮助的。希望无论如何。分享不会受到伤害。
关于java - 为编辑文本设置特定的语言环境,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24121085/