在编辑文本中按任意次数零,但用户只能在计算器中看到1位数

问题描述 投票:3回答:2

我有一个编辑文本来填充金额。所以,我添加了文本观察器,但我不希望用户“0000000 ...”如果用户将连续按“0000 ...”而不是它应该只显示一次“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")之后,它将进入无限循环。

android android-edittext calculator
2个回答
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);
            }
        }
    });

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");
            }
        }
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.