最近在做一个输入扫描银行卡的需求,要求通过card.io这个开源的sdk扫描获得银行卡号,或者直接输入卡号。那么在输入卡号的过程中,需要每4个数字自动空一格,实现起来也比较简单,主要是实现一个TextWacher的接口,然后重写里面的beforeTextChanged(),onTextChanged()以及afterTextChanged()三个方法。主要代码如下
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
public class SpaceText implements TextWatcher{
private String TAG = "SpaceText";
private EditText etSpace;
int beforeTextLength = 0;
int onTextLength = 0;
public SpaceText(EditText etSpace){
super();
this.etSpace = etSpace;
}
public String removeAllSpace(String str) {
String tmpstr=str.replace(" ","");
return tmpstr;
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
String str = etSpace.getText().toString();
Log.d(TAG, "mEditText = " + removeAllSpace(str) + ".");
onTextLength = str.length();
Log.d(TAG, "beforeLen = " + beforeTextLength + "afterLen = " + onTextLength);
if (onTextLength > beforeTextLength) {
if (str.length() == 5 || str.length() == 10 || str.length() == 15 || str.length() == 20) {
etSpace.setText(new StringBuffer(str).insert(
str.length() - 1, " ").toString());
etSpace.setSelection(etSpace.getText()
.length());
Log.d(TAG, "selection = " +etSpace.getText()
.length());
}
} else {
if (str.startsWith(" ")) {
etSpace.setText(new StringBuffer(str).delete(
onTextLength - 1, onTextLength).toString());
etSpace.setSelection(etSpace.getText()
.length());
Log.d(TAG, "else start space");
}
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
beforeTextLength = s.length();
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
}
首先创建一个类实现TextWatcher接口,重载构造方法来接受一个EditText类型的etSpace数据,这样在主函数中的EditText的控件里只用加入TextWatcher SpaceText = new SpaceText(EditText)将EditText传进去,然后 EditText.addTextChangedListener(SpaceText)设置监听即可。
代码比较简单,就当做一个小总结了。