银行卡号、电话号、身份证号 EditText 自定义格式的输入框

package com.yidian.AddSpaceEditText;

import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.widget.EditText;

/**
* Created by bmc on 2018/4/13.
*/

public class AddSpaceTextWatcher implements TextWatcher {


/** text改变之前的长度 */
private int beforeTextLength = 0;
private int onTextLength = 0;
private boolean isChanged = false;
private StringBuffer buffer = new StringBuffer();
/** 改变之前text空格数量 */
int spaceNumberA = 0;
private EditText editText;
/** text最大长度限制 */
private int maxLenght;
private SpaceType spaceType;
/** 记录光标的位置 */
private int location = 0;
/** 是否是主动设置text */
private boolean isSetText = false;

public AddSpaceTextWatcher(EditText editText, int maxLenght) {
this.editText = editText;
this.maxLenght = maxLenght;
if (editText == null) {
new NullPointerException("editText is null");
}
spaceType = SpaceType.defaultType;
editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
maxLenght) });
editText.addTextChangedListener(this);
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
beforeTextLength = s.length();
if (buffer.length() > 0) {
buffer.delete(0, buffer.length());
}
spaceNumberA = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') {
spaceNumberA++;
}
}
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
onTextLength = s.length();
buffer.append(s.toString());
if (onTextLength == beforeTextLength || onTextLength > maxLenght
|| isChanged) {
isChanged = false;
return;
}
isChanged = true;
}

@Override
public void afterTextChanged(Editable s) {
if (isChanged) {
location = editText.getSelectionEnd();
int index = 0;
while (index < buffer.length()) { // 删掉所有空格
if (buffer.charAt(index) == ' ') {
buffer.deleteCharAt(index);
} else {
index++;
}
}

index = 0;
int spaceNumberB = 0;
while (index < buffer.length()) { // 插入所有空格
spaceNumberB = insertSpace(index, spaceNumberB);
index++;
}

String str = buffer.toString();

// 下面是计算光位置的
if (spaceNumberB > spaceNumberA) {
location += (spaceNumberB - spaceNumberA);
spaceNumberA = spaceNumberB;
}
if (isSetText) {
location = str.length();
isSetText = false;
} else if (location > str.length()) {
location = str.length();
} else if (location < 0) {
location = 0;
}
updateContext(s,str);
isChanged = false;
}
}

/**
* 更新编辑框中的内容
*
* @param editable
* @param values
*/
private void updateContext(Editable editable,String values) {
if (spaceType == SpaceType.IDCardNumberType) {
editable.replace(0, editable.length(), values);
}else{
editText.setText(values);
try {
editText.setSelection(location);
} catch (Exception e) {
e.printStackTrace();
}
}
}

/**
* 根据类型插入空格
*
* @param index
* @param spaceNumberAfter
* @return
* @see [类、类#方法、类#成员]
*/
private int insertSpace(int index, int spaceNumberAfter) {
switch (spaceType) {
case defaultType:// 相隔四位空格
if (index > 3
&& (index % (4 * (spaceNumberAfter + 1)) == spaceNumberAfter)) {
buffer.insert(index, ' ');
spaceNumberAfter++;
}
break;
case bankCardNumberType:
if (index > 3
&& (index % (4 * (spaceNumberAfter + 1)) == spaceNumberAfter)) {
buffer.insert(index, ' ');
spaceNumberAfter++;
}
break;
case mobilePhoneNumberType:
if (index == 3
|| ((index > 7) && ((index - 3) % (4 * spaceNumberAfter) == spaceNumberAfter))) {
buffer.insert(index, ' ');
spaceNumberAfter++;
}
break;
case IDCardNumberType:
if (index == 6
|| ((index > 10) && ((index - 6) % (4 * spaceNumberAfter) == spaceNumberAfter))) {
buffer.insert(index, ' ');
spaceNumberAfter++;
}
break;
default:
if (index > 3
&& (index % (4 * (spaceNumberAfter + 1)) == spaceNumberAfter)) {
buffer.insert(index, ' ');
spaceNumberAfter++;
}
break;
}
return spaceNumberAfter;
}

/***
* 计算需要的空格数
*
* @return 返回添加空格后的字符串长度
* @see [类、类#方法、类#成员]
*/
private int computeSpaceCount(CharSequence charSequence) {
buffer.delete(0, buffer.length());
buffer.append(charSequence.toString());
int index = 0;
int spaceNumberB = 0;
while (index < buffer.length()) { // 插入所有空格
spaceNumberB = insertSpace(index, spaceNumberB);
index++;
}
buffer.delete(0, buffer.length());
return index;
}

/**
* 设置空格类型
*
* @param spaceType
* @see [类、类#方法、类#成员]
*/
public void setSpaceType(SpaceType spaceType) {
this.spaceType = spaceType;
if (this.spaceType == SpaceType.IDCardNumberType) {
editText.setInputType(InputType.TYPE_CLASS_TEXT);

//此处添加输入法的限制
String digits = "0123456789Xx ";
if(!TextUtils.isEmpty(digits)) {
editText.setKeyListener(DigitsKeyListener.getInstance(digits));
}
}
}

/**
* 设置输入字符
*
* @param charSequence
* @return 返回设置成功失败
* @see [类、类#方法、类#成员]
*/
public boolean setText(CharSequence charSequence) {
if (editText != null && !TextUtils.isEmpty(charSequence) && computeSpaceCount(charSequence) <= maxLenght) {
isSetText = true;
editText.removeTextChangedListener(this);
editText.setText(charSequence);
editText.addTextChangedListener(this);
return true;
}
return false;
}

/**
* 得到输入的字符串去空格后的字符串
*
* @return
* @see [类、类#方法、类#成员]
*/
public String getTextNotSpace() {
if (editText != null) {
return delSpace(editText.getText().toString());
}
return null;
}

/**
* 得到输入的字符串去空格后的长度
*
* @return
* @see [类、类#方法、类#成员]
*/
public int getLenghtNotSpace() {
if (editText != null) {
return getTextNotSpace().length();
}
return 0;
}

/**
* 得到空格数量
*
* @return
* @see [类、类#方法、类#成员]
*/
public int getSpaceCount() {
return spaceNumberA;
}

/**
* 去掉字符空格,换行符等
*
* @param str
* @return
* @see [类、类#方法、类#成员]
*/
private String delSpace(String str) {
if (str != null) {
str = str.replaceAll("\r", "");
str = str.replaceAll("\n", "");
str = str.replace(" ", "");
}
return str;
}
/**
* 空格类型
*/
public enum SpaceType {
/** 默认类型 */
defaultType,
/** 银行卡类型 */
bankCardNumberType,
/** 手机号类型 */
mobilePhoneNumberType,
/** 身份证类型 */
IDCardNumberType;
}

}

具体的用法

public class MainActivity extends AppCompatActivity {
    private AddSpaceTextWatcher[] asEditTexts=new AddSpaceTextWatcher[3];
    private EditText[] editTexts=new EditText[3];
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editTexts[0]=(EditText)findViewById(R.id.editText);//银行卡
        editTexts[1]=(EditText)findViewById(R.id.editText2);//手机号
        editTexts[2]=(EditText)findViewById(R.id.editText3);//身份证
        asEditTexts[0]=new AddSpaceTextWatcher(editTexts[0],48);
        asEditTexts[0].setSpaceType(AddSpaceTextWatcher.SpaceType.bankCardNumberType);
        asEditTexts[1]=new AddSpaceTextWatcher(editTexts[1],13);
        asEditTexts[1].setSpaceType(AddSpaceTextWatcher.SpaceType.mobilePhoneNumberType);
        asEditTexts[2]=new AddSpaceTextWatcher(editTexts[2],21);
        asEditTexts[2].setSpaceType(AddSpaceTextWatcher.SpaceType.IDCardNumberType);
    }
}

在布局文件中的使用

<?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="com.robin.lazy.text.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/textView" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:singleLine="true"
        android:id="@+id/editText"
        android:hint="银行卡类型"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:singleLine="true"
        android:hint="手机号类型"
        android:id="@+id/editText2"
        android:layout_below="@+id/editText"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="45dp" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="numberSigned"
        android:singleLine="true"
        android:hint="身份证类型"
        android:id="@+id/editText3"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

 

转载于:https://www.cnblogs.com/bimingcong/p/8821346.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值