Android EditTextView 实现带空格分隔的输入(电话号码,银行卡)
时间:2020-11-03 13:45:54|栏目:Android代码|点击: 次
电话号码输入框需求:
- 三位,七位后有空格
- 删除倒数第四,第八位会将空格也删除
使用TextWatcher
When an object of a type is attached to an Editable, its methods will be called when the text is changed.就是说,只要是一个可编辑的文本设置了TextWatcher,当文本发生变化时,TextWatcher里的方法将会被调用.
其实不难,看了网上搜索到的例子,思路绕了点,这边做一份自己的记录
import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.widget.EditText; /** * @desc * @autor Xemenes * @time 2017/5/12 10:18 */ public class PhoneNumberTextWatcher implements TextWatcher { EditText editText; int lastContentLength = 0; boolean isDelete = false; public PhoneNumberTextWatcher(EditText editText) { this.editText = editText; } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { StringBuffer sb = new StringBuffer(s); //是否为输入状态 isDelete = s.length() > lastContentLength ? false : true; //输入是第4,第9位,这时需要插入空格 if(!isDelete&& (s.length() == 4||s.length() == 9)){ if(s.length() == 4) { sb.insert(3, " "); }else { sb.insert(8, " "); } setContent(sb); } //删除的位置到4,9时,剔除空格 if (isDelete && (s.length() == 4 || s.length() == 9)) { sb.deleteCharAt(sb.length() - 1); setContent(sb); } lastContentLength = sb.length(); } @Override public void afterTextChanged(Editable s) { } /** * 添加或删除空格EditText的设置 * * @param sb */ private void setContent(StringBuffer sb) { editText.setText(sb.toString()); //移动光标到最后面 editText.setSelection(sb.length()); } }
总结
栏 目:Android代码
下一篇:21天学习android开发教程之SurfaceView
本文标题:Android EditTextView 实现带空格分隔的输入(电话号码,银行卡)
本文地址:http://www.codeinn.net/misctech/18798.html