我以编程方式创建了一个编辑文本并添加了一个文本观察器,我的代码如下所示:
txtPrice = new EditText(this);
txtPrice.setHint("Price");
txtPrice.setTextColor(Color.GRAY);
txtPrice.setGravity(Gravity.CENTER_VERTICAL);
txtPrice.setTextSize(20);
txtPrice.setPadding(20, 0, 0, 0);
txtPrice.setBackgroundColor(Color.WHITE);
txtPrice.addTextChangedListener(new NumberTextWatcher(txtPrice));
txtPrice.setFilters(new InputFilter[] { new InputFilter.LengthFilter(9) });
txtPrice.setInput
Type(InputType.TYPE_CLASS_NUMBER);
此类为添加的任何数字添加一个逗号,例如:1,356,785
当我将它添加到通常定义的编辑文本时:
@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);
}
目前它只增加了一个空格。有人对我有任何帮助或建议吗?我不明白为什么这不想工作。