Android 自定义手机输入框

1. 自定义类PhoneTextView

PhoneTextView继承EditText,在构造函数里面可以初始化类型,限定长度和输入类型,并添加TextWatcher监听器。

public class PhoneTextView extends EditText {

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

    public PhoneTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

        setFilters(new InputFilter[] {new InputFilter.LengthFilter(13)});
        setInputType(InputType.TYPE_CLASS_NUMBER);

        new PhoneTextWatcher(this);
    }

}

2. 自定义TextWatcher

TextWatcher主要用于监听EditText的文本变化,详情可见TextWatcher监听器
覆盖onTextChanged()方法,去除空格,并调整光标的位置。

static class PhoneTextWatcher implements TextWatcher {
    private static final char SPACE_CHAR = ' ';

    private EditText mEditText;

    PhoneTextWatcher(EditText editText) {
        this.mEditText = editText;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        int selection = start + count;

        char[] array = new char[s.length()];
        int len = 0;
        int space = 0;
        for (int index = 0; index < s.length(); index++) {
            if (s.charAt(index) == SPACE_CHAR) {
                if (index < selection) {
                    ++space;
                }
            } else {
                array[len++] = s.charAt(index);
            }
        }
        setPhoneText(new String(array, 0, len), selection - space);
    }

    @Override
    public void afterTextChanged(Editable s) {
    }
}

setPhoneText()方法,通过isEmptyPlace(int)方法来判断是否需要添加空格,并调整光标。在设置新的字符时,要先关闭监听器。

private void setPhoneText(String phoneText, int selection) {
    LogTool.logi("PhoneTextView", phoneText + ", selection = " + selection);
    String text = "";
    int space = 0;
    for (int index = 0; index < phoneText.length(); index++) {
        if (isEmptyPlace(text.length())) {
            text += SPACE_CHAR;
            if (index < selection) {
                ++space;
            }
        }
        text += phoneText.charAt(index);
    }

    mEditText.removeTextChangedListener(this);
    mEditText.setText(text);
    mEditText.setSelection(selection + space);
    mEditText.addTextChangedListener(this);
}

private boolean isEmptyPlace(int index) {
    return 3 == index || 8 == index;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值