Android实现输入手机号时自动添加空格

http://www.devwiki.net/2015/10/07/Android-TextWatcher-Add-Space-To-Phone_Number/

activity_main.xml



    

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) {

        }
    };
}

效果图:

Android实现输入手机号时自动添加空格_第1张图片

你可能感兴趣的:(android基础)