今天朋友让我帮忙搞个Imei的格式,我想这还不简单,一顿猛敲后,发现丫的光标位置好坑,现在我记录下我的思路,如果有不好的地方或有待改进的地方,还请各位大佬下面留言,先来个效果图
下面是代码
package com.gongwenbo.demo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
/**
* Imei智能格式填补 12:34:56
*/
public class ImeiActivity extends AppCompatActivity {
private EditText mEt;
private int preLength;
private boolean flagAfter = true;
private boolean flag = true;
int index = 0;
private static final String TAG = "ImeiActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_imei);
mEt = (EditText) findViewById(R.id.et);
mEt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// 获取光标的位置
index = mEt.getSelectionStart();
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
String content = editable.toString();
// 判断是添加还是删除,此处要获取第一次的值,因为重新赋值了,他还会走一次
if (flagAfter) {
flag = preLength > content.length() ? true : false;
}
flagAfter = !flagAfter;
// 判断值是否一样,防止死循环
if (preLength == content.length()) {
return;
}
// 添加格式,我的是 12:34:45 自行添加
content = content.replace(":", "");
char[] chars = content.toCharArray();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < chars.length; i++) {
stringBuilder.append(chars[i]);
if (i % 2 == 1 && i != chars.length - 1) {
stringBuilder.append(":");
}
}
preLength = stringBuilder.length();
String msg = stringBuilder.toString();
mEt.setText(msg);
// 防止数组越界
if (index > preLength) {
index = preLength;
}
// 如果是添加的话,光标要往后移1
if (!flag && index >= 1 && msg.toCharArray()[index - 1] == ':') {
index = index + 1;
}
// 设置光标的位置
mEt.setSelection(index);
}
});
}
}