在android中格式化EditText

时间:2014-12-29 12:11:28

标签: android android-edittext format

我想在编辑文本中输入值时输入特定格式。

例如,当输入120000时,它自动设置为1,20,000.00 inmy编辑文本。

如何在文本观察器中设置这种格式?

1 个答案:

答案 0 :(得分:1)

使用textwatcher如下:

private class GenericTextWatcher implements TextWatcher{

        private View view;
        private GenericTextWatcher(View view) {
            this.view = view;
        }

        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
        public void onTextChanged(CharSequence s, int i, int i1, int i2) {

            switch(view.getId()){
            case R.id.ed_youredittextid://this is your xml id
                 insertCommaIntoNumber(ed_youredittextid,s);
                break;
         }
        }

        public void afterTextChanged(Editable editable) {

        }
    }

        private void insertCommaIntoNumber(EditText etText,CharSequence s)
        {
            try {
                if (s.toString().length() > 0) 
                {
                    String convertedStr = s.toString();
                    if (s.toString().contains(".")) 
                    {
                        if(chkConvert(s.toString()))
                            convertedStr = customFormat("###,###.##",Double.parseDouble(s.toString().replace(",","")));
                    } 
                    else
                    {
                        convertedStr = customFormat("###,###.##", Double.parseDouble(s.toString().replace(",","")));
                    }

                    if (!etText.getText().toString().equals(convertedStr) && convertedStr.length() > 0) {
                        etText.setText(convertedStr);
                        etText.setSelection(etText.getText().length());
                    }
                }

            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }


 public String customFormat(String pattern, double value) {
        DecimalFormat myFormatter = new DecimalFormat(pattern);
        String output = myFormatter.format(value);
        return output;
    }

    public boolean chkConvert(String s)
    {
        String tempArray[] = s.toString().split("\\.");
        if (tempArray.length > 1) 
        {
            if (Integer.parseInt(tempArray[1]) > 0) {
                return true;
            }
            else 
                return false;
        }
        else
            return false;
    } 

要调用textwathcher,你必须这样做:

edyourdittext.addTextChangedListener(new GenericTextWatcher(edyouredittext));
//this is the edittext with which you want to bind the textwatcher