在编辑文本中多次按零,但用户只能看到1位数字,例如“计算器”

时间:2019-02-10 14:15:00

标签: android android-edittext calculator

我有一个编辑文字可以填写金额。因此,我添加了文本监视程序,但是我不希望用户连续按下“ 0000 ...”来将其设置为“ 0000000 ...”,而应该像计算器一样仅显示一次“ 0”

我该怎么做?

private void setAmount() {
    etAmount.addTextChangedListener(new TextWatcher() {

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

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.length() == 1) {
                if (s.toString().equals("0")) {
                    etAmount.setText("0");
                }
            }

            //Not working
        }

        @Override
        public void afterTextChanged(Editable s) {}
    });
}

我认为,我的逻辑也是错误的,因为当我输入单个输入并检查s.length时,并且在et.setText("0")之后,它将进入无限循环。

2 个答案:

答案 0 :(得分:1)

尝试一下:

    etAmount.addTextChangedListener(new TextWatcher() {

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

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

        @Override
        public void afterTextChanged(Editable s) {
            String text = s.toString();
            if (text.length() == 2 && text.charAt(0) == '0') {
                etAmount.setText(text.substring(1));
                etAmount.setSelection(1);
            }
        }
    });

答案 1 :(得分:0)

您可以这样做:

etAmount.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

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

    @Override
    public void afterTextChanged(Editable s) {
        if (s.length() == 2) {
            if (s.toString().startsWith("00")) {
                etAmount.setText("0");
            }
        }
    }
});