在6个字母后自动在EditText中添加字符

odi*_*iil 5 android android-edittext

我希望在我的EditText中自动在6个字母后加上" - ",我希望用户可以在" - "之后继续写.(我希望用户写道:1234562,它在EditText中显示为123456-2).

但我不知道如何做到这一点,如果可能的话.如果你可以帮助我,谢谢

kga*_*oid 11

添加一个textwatcher.然后使用以下代码:

@Override
public void afterTextChanged(Editable text) {     


    if (text.length() == 6) {
        text.append('-');
    }


}
Run Code Online (Sandbox Code Playgroud)

您还可以在if语句中使用多个条件,如:

 if (text.length() == 3 || text.length() == 6) {
        text.append('-');
    }
Run Code Online (Sandbox Code Playgroud)


小智 6

您还可以使用以下命令删除字符:

text.addTextChangedListener(new TextWatcher() {
        int first = 0;
        int second;

        @Override
        public void afterTextChanged(Editable s) {
            second = first;
            first = s.length();

            if(text.length()==6 && first>second){
                text.append("-");
            }
        }
Run Code Online (Sandbox Code Playgroud)