Android自定义EditText实现手机号码和银行卡号自动分隔、自动设置分隔格式

1. 在原作者的基础上,删除了多余的功能,以及不依赖任何资源等文件;要用的话直接把自定义的类放进项目中即可,,,也不用     加入jar包。

2.功能点

* 按自己想要的格式自动分割显示的EditText 默认手机格式:xxx xxxx xxxx

* 也可自定义任意格式,如信用卡格式:xxxx-xxxx-xxxx-xxxx 或 xxxx xxxx xxxx xxxx

* 使用pattern时无需在xml中设置maxLength属性,若需要设置时应注意加上分隔符的数

效果图:

 

自定义的类:

package nie.com.testphoneparrtern;

import android.content.Context;
import android.graphics.Canvas;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.AttributeSet;



/**
 * 按自己想要的格式自动分割显示的EditText 默认手机格式:xxx xxxx xxxx可
 * 也可自定义任意格式,如信用卡格式:xxxx-xxxx-xxxx-xxxx 或 xxxx xxxx xxxx xxxx
 * 使用pattern时无需在xml中设置maxLength属性,若需要设置时应注意加上分隔符的数量
 * com.z.customedittext.XEditText
 * ContentSeparatorEditText
 */

public class XEditText extends android.support.v7.widget.AppCompatEditText {



    private static final String SPACE = " ";
    private static final int[] DEFAULT_PATTERN = new int[] { 3, 4, 4 };

    private OnTextChangeListener mTextChangeListener;
    private TextWatcher mTextWatcher;

    private int preLength;
    private int currLength;

    private int[] pattern; // 模板
    private int[] intervals; // 根据模板控制分隔符的插入位置
    private String separator; // 分割符,默认使用空格分割
    // 根据模板自动计算最大输入长度,超出输入无效。使用pattern时无需在xml中设置maxLength属性,若需要设置时应注意加上分隔符的数量
    private int maxLength;
    private boolean hasNoSeparator; // 设置为true时功能同EditText




    public XEditText(Context context) {
        this(context, null);
    }

    public XEditText(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.editTextStyle); // Attention !
    }

    public XEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        if (separator == null)
            separator = SPACE;
        init();
    }



    private void init() {
        // 如果设置 inputType="number" 的话是没法插入空格的,所以强行转为inputType="phone"
        if (getInputType() == InputType.TYPE_CLASS_NUMBER)
            setInputType(InputType.TYPE_CLASS_PHONE);
        setPattern(DEFAULT_PATTERN);
        mTextWatcher = new MyTextWatcher();
        this.addTextChangedListener(mTextWatcher);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }


    /**
     * 自定义分隔符
     */
    public void setSeparator(String separator) {
        if (separator == null) {
            throw new IllegalArgumentException("separator can't be null !");
        }
        this.separator = separator;
    }



    /**
     * 自定义分割模板
     * @param pattern 每一段的字符个数的数组
     */
    public void setPattern(int[] pattern) {
        if (pattern == null) {
            throw new IllegalArgumentException("pattern can't be null !");
        }
        this.pattern = pattern;
        intervals = new int[pattern.length];
        int count = 0;
        int sum = 0;
        for (int i = 0; i < pattern.length; i++) {
            sum += pattern[i];
            intervals[i] = sum + count;
            if (i < pattern.length - 1)
                count++;
        }
        maxLength = intervals[intervals.length - 1];

    }



    /**
     * 输入待转换格式的字符串
     */
    public void setTextToSeparate(CharSequence c) {
        if (c == null || c.length() == 0)
            return;
        setText("");
        for (int i = 0; i < c.length(); i++) {
            append(c.subSequence(i, i + 1));
        }
    }



    /**
     * 获得除去分割符的输入框内容
     */
    public String getNonSeparatorText() {
        return getText().toString().replaceAll(separator, "");
    }


    /**
     * @return 是否有分割符
     */
    public boolean hasNoSeparator() {
        return hasNoSeparator;
    }

    /**
     * @param hasNoSeparator true设置无分隔符模式,功能同EditText
     */
    public void setHasNoSeparator(boolean hasNoSeparator) {
        this.hasNoSeparator = hasNoSeparator;
        if (hasNoSeparator)
            separator = "";
    }

    /**
     * 设置OnTextChangeListener,同EditText.addOnTextChangeListener()
     */
    public void setOnTextChangeListener(OnTextChangeListener listener) {
        this.mTextChangeListener = listener;
    }


    // =========================== MyTextWatcher===========================
    private class MyTextWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            preLength = s.length();
            if (mTextChangeListener != null)
                mTextChangeListener.beforeTextChanged(s, start, count, after);
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            currLength = s.length();
            if (hasNoSeparator)
                maxLength = currLength;
            if (currLength > maxLength) {
                getText().delete(currLength - 1, currLength);
                return;
            }
            for (int i = 0; i < pattern.length; i++) {
                if (currLength == intervals[i]) {
                    if (currLength > preLength) { // 正在输入
                        if (currLength < maxLength) {
                            removeTextChangedListener(mTextWatcher);
                            mTextWatcher = null;
                            getText().insert(currLength, separator);
                        }
                    } else if (preLength <= maxLength) { // 正在删除
                        removeTextChangedListener(mTextWatcher);
                        mTextWatcher = null;
                        getText().delete(currLength - 1, currLength);
                    }
                    if (mTextWatcher == null) {
                        mTextWatcher = new MyTextWatcher();
                        addTextChangedListener(mTextWatcher);
                    }
                    break;
                }
            }
            if (mTextChangeListener != null)
                mTextChangeListener.onTextChanged(s, start, before, count);
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (mTextChangeListener != null)
                mTextChangeListener.afterTextChanged(s);
        }
    }


    public interface OnTextChangeListener {
        void beforeTextChanged(CharSequence s, int start, int count, int after);
        void onTextChanged(CharSequence s, int start, int before, int count);
        void afterTextChanged(Editable s);
    }





}

 布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_gravity="center"
    android:gravity="center"
    tools:context=".MainActivity">

    <nie.com.testphoneparrtern.XEditText
        android:id="@+id/edt"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_gravity="center"
        android:gravity="center"
        android:hint="请输入" />

    <Button
        android:id="@+id/bt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="按钮"
        />

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

</LinearLayout>

 MainActivity.java

package nie.com.testphoneparrtern;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

    private XEditText edt;
    private Button bt;
    private TextView tv;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edt=(XEditText)findViewById(R.id.edt);
        bt=(Button)findViewById(R.id.bt);
        tv=(TextView)findViewById(R.id.tv);

        //设置分隔的条件
         //信用卡格式
//        edt.setPattern(new int[] { 4, 4, 4, 4, 4 });
        //电话号码格式
        edt.setPattern(new int[] { 3, 4, 4 });
        //设置分隔符
        edt.setSeparator("-");


        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edt.setTextToSeparate("13356258951");
            }
        });

        edt.setOnTextChangeListener(new XEditText.OnTextChangeListener() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                tv.setText(edt.getNonSeparatorText());
            }
        });

    }




}

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值