EditText输入手机号自动带空格

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了EditText输入手机号自动带空格相关的知识,希望对你有一定的参考价值。

xml:

<EditText
android:id="@+id/edit_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入手机号"
android:inputType="number"
android:maxLength="13"/>

Activity:

mEditText = (EditText) findViewById(R.id.edit_main);
mEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {

}

@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
if (charSequence == null || charSequence.length() == 0)
return;
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < charSequence.length(); i++) {
if (i != 3 && i != 8 && charSequence.charAt(i) == ‘ ‘) {
continue;
} else {
stringBuilder.append(charSequence.charAt(i));
if ((stringBuilder.length() == 4 || stringBuilder.length() == 9)
&& stringBuilder.charAt(stringBuilder.length() - 1) != ‘ ‘) {
stringBuilder.insert(stringBuilder.length() - 1, ‘ ‘);
}
}
}
if (!stringBuilder.toString().equals(charSequence.toString())) {
int index = start + 1;
if (stringBuilder.charAt(start) == ‘ ‘) {
if (before == 0) {
index++;
} else {
index--;
}
} else {
if (before == 1) {
index--;
}
}
mEditText.setText(stringBuilder.toString());
mEditText.setSelection(index);
}
}

@Override
public void afterTextChanged(Editable s) {

}
});

以上是关于EditText输入手机号自动带空格的主要内容,如果未能解决你的问题,请参考以下文章

焦点在 EditText 上时 ViewPager2 片段内容消失

请问在EditText中空格自动换行问题怎么解决?

jQuery实现手机号正则验证输入及自动填充空格功能

Android 带清除功能的输入框控件EditText

Android EditText手机号格式化输入XXX-XXXX-XXXX

35.Android之带删除按钮EditText学习