Android 實現EditText輸入數字時每三位加逗號

public static void inputWithCommaListener(final EditText editText) {

    editText.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {

            if (count != before) {
                String sss = "";
                String string = s.toString().replace(",", "");
                int b = string.length() / 3;
                if (string.length() >= 3 ) {
                    int yushu = string.length() % 3;
                    if (yushu == 0) {
                        b = string.length() / 3 - 1;
                        yushu = 3;
                    }
                    for (int i = 0; i < b; i++) {
                        sss = sss + string.substring(0, yushu) + "," + string.substring(yushu, 3);
                        string = string.substring(3, string.length());
                    }
                    sss = sss + string;
                    editText.setText(sss);
                }
            }
            editText.setSelection(editText.getText().length());
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
        }

    });
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章