开发者

afterTextChanged deleting issue

I tried to set this up so that when I enter something into the EditText field, it will change the text color and set a variable to the value of the numbers entered. However, when I delete the characters from the field, it triggers an error that closes the app. I think I may either need to find an if statement that doesn't rely on length, or maybe use some of the other methods (onTextChanged, beforeTextChanged... I don't really know how to use either of those correctly though)

    public void after开发者_开发技巧TextChanged(Editable arg0) {
    if(arg0.length()>0){
        ageTag.setTextColor(Color.GREEN);
        ageEntered=true;
        ageInYears=Integer.parseInt(enterAge.getText().toString()); 
    }
}


  1. Implement the android.text.TextWatcher interface

  2. Bind a listener:

enterAge.addTextChangedListener(this);


I had a similar problem. I had to append "-" after 5th char, 11th etc. When I wanted to delete the "-" it was ignoring the delete key, so what I did is the following.

Created two variables: beforeCharCounter and charCounter and in onTextChanged I have set their values on before and count.

activationKeyEditText.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) {
            beforeCharCounter = before;
            charCounter = count;
            System.out.println(count);
        }

        @Override
        public void afterTextChanged(Editable s) {
            if ((s.length() == 5 && beforeCharCounter <= 5 && charCounter == 5) ||
                    (s.length() == 11 && beforeCharCounter <= 11 && charCounter == 11)
                    || (s.length() == 17 && beforeCharCounter <= 17 && charCounter == 17)) {
                s.append('-');
            }
        }
    });

if the value of the before is bigger then the length then for sure it is delete and this will solve the delete issue. The count is used for when the user has entered 10 chars and he press on the 5th one. If we don't keep the exact count dashes will be appended at the end like crazy.

Hope this will help you solve the issue.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜