http://www.devwiki.net/2015/10/07/Android-TextWatcher-Add-Space-To-Phone_Number/
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<EditText
android:id="@+id/id_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLength="13"
android:singleLine="true"
android:phoneNumber="true"/>
</RelativeLayout>
MainActivity.java
package com.lxm.photonumber;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.id_edittext);
editText.addTextChangedListener(textWatch);
}
private TextWatcher textWatch = 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) {
if (count == 1) {
int length = s.toString().length();
if (length == 3 || length == 8) {
editText.setText(s + " ");
editText.setSelection(editText.getText().toString().length());
}
}
}
@Override
public void afterTextChanged(Editable s) {
}
};
}
效果图: