android设置4个字符,android format edittext在每4个字符后显示空格

格式的文本是000 000 0000

public class PhoneNumberTextWatcher implements TextWatcher {

private static final String TAG = PhoneNumberTextWatcher.class

.getSimpleName();

private EditText edTxt;

private boolean isDelete;

public PhoneNumberTextWatcher(EditText edTxtPhone) {

this.edTxt = edTxtPhone;

edTxt.setOnKeyListener(new View.OnKeyListener() {

@Override

public boolean onKey(View v, int keyCode, KeyEvent event) {

if (keyCode == KeyEvent.KEYCODE_DEL) {

isDelete = true;

}

return false;

}

});

}

public void onTextChanged(CharSequence s, int start, int before, int count) {

}

public void beforeTextChanged(CharSequence s, int start, int count,

int after) {

}

public void afterTextChanged(Editable s) {

if (isDelete) {

isDelete = false;

return;

}

String val = s.toString();

String a = "";

String b = "";

String c = "";

if (val != null && val.length() > 0) {

val = val.replace(" ", "");

if (val.length() >= 3) {

a = val.substring(0, 3);

} else if (val.length() < 3) {

a = val.substring(0, val.length());

}

if (val.length() >= 6) {

b = val.substring(3, 6);

c = val.substring(6, val.length());

} else if (val.length() > 3 && val.length() < 6) {

b = val.substring(3, val.length());

}

StringBuffer stringBuffer = new StringBuffer();

if (a != null && a.length() > 0) {

stringBuffer.append(a);

if (a.length() == 3) {

stringBuffer.append(" ");

}

}

if (b != null && b.length() > 0) {

stringBuffer.append(b);

if (b.length() == 3) {

stringBuffer.append(" ");

}

}

if (c != null && c.length() > 0) {

stringBuffer.append(c);

}

edTxt.removeTextChangedListener(this);

edTxt.setText(stringBuffer.toString());

edTxt.setSelection(edTxt.getText().toString().length());

edTxt.addTextChangedListener(this);

} else {

edTxt.removeTextChangedListener(this);

edTxt.setText("");

edTxt.addTextChangedListener(this);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值