项目中需要做这个功能,本来想偷个懒网上找一下,找了几个发现写的太复杂了,而且还有问题。
几行代码就能解决的算法,分享一下!
private TextWatcher mTextWatcher = new TextWatcher() {
int beforeLength;
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
beforeLength = s.length();
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mBtnOk.setEnabled(s.length() == 19);
}
//一般我们都是在这个里面进行我们文本框的输入的判断,上面两个方法用到的很少
@Override
public void afterTextChanged(Editable s) {
int length = s.toString().length();
boolean b = s.toString().endsWith(" ");
if (beforeLength < length) { //判断输入状态
if (length == 4 || length == 9 || length == 14) {
mEtCardId.setText(new StringBuffer(s).insert(length, " ").toString());
} else if (length == 5 || length == 10 || length == 15) {//另一种情况,手动删除空格再次输入后
if (!b) {
mEtCardId.setText(new StringBuffer(s).insert(length - 1, " ").toString());
}
}
} else { //删除状态
if (b) {
mEtCardId.setText(new StringBuffer(s).delete(length - 1, length).toString());
}
}
//设置指针选中位置
mEtCardId.setSelection(mEtCardId.getText().toString().length());
}
};
这是一个学习用的金融项目,搞了一堆东西。感兴趣的请到github下载
https://github.com/Everglowzz/P2P
网友评论