发现《蓝牙串口》和《TCP连接》的十六进制编辑框在输入时还要自己注意添加空格太不智能了,又容易出错。所以就想着在每输入两个字符后自动加入一个空格(两个字符代表一个十六进制数,刚好可以转成一个BYTE),然后删除字符时,可以自动删除空格(不懂怎么表述,运行一下代码就知道了)。
方法:使用EditText的addTextChangedListener接口,并实现TextWatcher。具体实现代码如下:
TextWatcher autoAddSpaceTextWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (count == 1) {
if ((s.length() + 1) % 3 == 0) {
setText(s + " ");
setSelection(s.length() + 1);
}
} else if (count == 0) {
if (s.length() > 0 && s.length() % 3 == 0) {
setText(s.subSequence(0, s.length() - 1));
setSelection(s.length() - 1);
}
}
}
@Override
public void afterTextChanged(Editable editable) {}
}; |
TextWatcher autoAddSpaceTextWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (count == 1) {
if ((s.length() + 1) % 3 == 0) {
setText(s + " ");
setSelection(s.length() + 1);
}
} else if (count == 0) {
if (s.length() > 0 && s.length() % 3 == 0) {
setText(s.subSequence(0, s.length() - 1));
setSelection(s.length() - 1);
}
}
}
@Override
public void afterTextChanged(Editable editable) {}
};
最后调用addTextChangedListener传入autoAddSpaceTextWatcher即可!赶紧去体验新版《蓝牙串口》和《TCP连接》的十六进制输入吧!