我试图以编程方式设置EditText的数字值,格式为“9,999”(其中9为数字0-9)。到目前为止,我有:
final EditText editText = new EditText(v.getContext());
editText.setLayoutParams(params);
editText.setText("");
editText.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLenght)});
editText.addTextChangedListener(new TextWatcher() {
int len=0;
//int count=0;
@Override
public void afterTextChanged(Editable s) {
String str = editText.getText().toString();
if(str.length()==1&& len <str.length()){//len check for backspace
editText.append(",");
}
}
@Override
public void beforeTextChanged(CharSequence c, int arg1, int arg2, int arg3) {
String str = editText.getText().toString();
len = str.length();
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String str = editText.getText().toString();
}
});
哪个不是最好的,因为:
有什么想法吗?
答案 0 :(得分:3)
您可以尝试将afterTextChange()
方法更改为此
@Override
public void afterTextChanged(Editable s) {
try {
String str = String.format("%,d", Long.parseLong(s.toString()
.replaceAll(",", "")));
int pos = editText.getSelectionStart();
editText.removeTextChangedListener(this);
editText.setText(str);
editText.setSelection(pos);
editText.addTextChangedListener(this);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}