Android :强制使用点而不是带有十进制 EditTexts 的逗号
Android : Force the use of the dot instead of the comma with decimal EditTexts
如何在十进制 EditText 中强制使用点而不是逗号?
String.replace(",", ".") 对我来说不是有效的解决方案。
我虽然以编程方式设置美国语言环境,但它也改变了语言。
有没有办法在不更改语言的情况下更改语言环境?
您可以针对不同的语言环境使用以下内容
private void localeDecimalInput(final EditText editText){
DecimalFormat decFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.getDefault());
DecimalFormatSymbols symbols=decFormat.getDecimalFormatSymbols();
final String defaultSeperator=Character.toString(symbols.getDecimalSeparator());
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable editable) {
if(editable.toString().contains(defaultSeperator))
editText.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
else
editText.setKeyListener(DigitsKeyListener.getInstance("0123456789" + defaultSeperator));
}
});
}
或解决方案2
使用 EditText
与 android:inputType="numberDecimal"
和 android:digits="0123456789.,"
.
然后在EditText
中添加一个TextChangedListener
,如下afterTextChanged
:
public void afterTextChanged(Editable s) {
double doubleValue = 0;
if (s != null) {
try {
doubleValue = Double.parseDouble(s.toString().replace(',', '.'));
} catch (NumberFormatException e) {
//Error
}
}
//Do something with doubleValue
}
如何在十进制 EditText 中强制使用点而不是逗号?
String.replace(",", ".") 对我来说不是有效的解决方案。
我虽然以编程方式设置美国语言环境,但它也改变了语言。
有没有办法在不更改语言的情况下更改语言环境?
您可以针对不同的语言环境使用以下内容
private void localeDecimalInput(final EditText editText){
DecimalFormat decFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.getDefault());
DecimalFormatSymbols symbols=decFormat.getDecimalFormatSymbols();
final String defaultSeperator=Character.toString(symbols.getDecimalSeparator());
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable editable) {
if(editable.toString().contains(defaultSeperator))
editText.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
else
editText.setKeyListener(DigitsKeyListener.getInstance("0123456789" + defaultSeperator));
}
});
}
或解决方案2
使用 EditText
与 android:inputType="numberDecimal"
和 android:digits="0123456789.,"
.
然后在EditText
中添加一个TextChangedListener
,如下afterTextChanged
:
public void afterTextChanged(Editable s) {
double doubleValue = 0;
if (s != null) {
try {
doubleValue = Double.parseDouble(s.toString().replace(',', '.'));
} catch (NumberFormatException e) {
//Error
}
}
//Do something with doubleValue
}