How to use EditText onTextChanged event when I press the number?

前端 未结 6 592
自闭症患者
自闭症患者 2020-11-30 06:40

I have an EditText with \"text = 0.00\". When I press the number 3, it should be like 0.03 and the second time when I press the number

6条回答
  •  悲哀的现实
    2020-11-30 07:03

    Here, I wrote something similar to what u need:

        inputBoxNumberEt.setText(".     ");
        inputBoxNumberEt.setSelection(inputBoxNumberEt.getText().length());
        inputBoxNumberEt.addTextChangedListener(new TextWatcher() {
    
            boolean ignoreChange = false;
    
            @Override
            public void afterTextChanged(Editable s) {
            }
    
            @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 (!ignoreChange) {
                    String string = s.toString();
                    string = string.replace(".", "");
                    string = string.replace(" ", "");
                    if (string.length() == 0)
                        string = ".     ";
                    else if (string.length() == 1)
                        string = ".  " + string;
                    else if (string.length() == 2)
                        string = "." + string;
                    else if (string.length() > 2)
                        string = string.substring(0, string.length() - 2) + "." + string.substring(string.length() - 2, string.length());
                    ignoreChange = true;
                    inputBoxNumberEt.setText(string);
                    inputBoxNumberEt.setSelection(inputBoxNumberEt.getText().length());
                    ignoreChange = false;
                }
            }
        });
    

提交回复
热议问题