使用过滤器以编程方式设置EditText数字

时间:2014-02-22 20:33:39

标签: java android

我试图以编程方式设置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();
     }     
});

哪个不是最好的,因为:

  • DigitsKeyListener不接受“,”分隔符。
  • 当我输入“1,0”时 然后去2x退格我可以输入“11111”。我必须去3x退格 然后当我输入“11111”时,它将是“1,1111”

有什么想法吗?

1 个答案:

答案 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();
    }
}