EditText not updated after text changed in the TextWatcher

后端 未结 1 1860
旧巷少年郎
旧巷少年郎 2020-12-11 21:18

I have an EditText and a TextWatcher.

Skeleton of my code:

EditText x;
x.addTextChangedListener(new XyzTextWatcher());

XyzTextWatcher implements Tex         


        
相关标签:
1条回答
  • 2020-12-11 21:52

    Ok, you never actually change the EditText just the Editable. Android EditTexts are not children of the Editable class. Strings are subclasses of the Editable class. The onTextChangedListener doesn't receive the EditText as an argument but the Editable/String displayed in the EditText. After you format the Editable with the hyphens you then need to update the EditText. Something like this should work fine:

    class MyClass extends Activity{
    
        //I've ommited the onStart(), onPause(), onStop() etc.. methods
    
        EditText x;
        x.addTextChangedListener(new XyzTextWatcher());
    
        XyzTextWatcher implements TextWatcher() {
            public synchronized void afterTextChanged(Editable text) {
                String s = formatText(text);
                MyClass.this.x.setText(s);
            }
        }
    
    }
    

    To prevent the slowdown why not change the formatText method something like this?

    private Editable formatText(Editable text) {
        int sep1Loc = 3;
        int sep2Loc = 7;
    
        if(text.length==sep1Loc)
        text.append('-');
    
        if(text.length==sep2Loc)
        text.append('-');
    
        return text;
    }
    

    Note: I haven't tested this

    0 讨论(0)
提交回复
热议问题