android 格式化输入控制
来源:互联网 发布:js中转换日期格式 编辑:程序博客网 时间:2024/05/29 02:15
Article from : http://horribile.blogspot.com/2011/11/formatting-edittext-input-with-regular.html
It will be the short article. Now we will format text in EditText with regular expressions.
The simple class will extend Input Filter:
- public class PartialRegexInputFilter implements InputFilter {
- private Pattern mPattern;
- public PartialRegexInputFilter(String pattern){
- mPattern = Pattern.compile(pattern);
- }
- @Override
- public CharSequence filter(CharSequence source,
- int sourceStart, int sourceEnd,
- Spanned destination, int destinationStart,
- int destinationEnd)
- {
- String textToCheck = destination.subSequence(0, destinationStart).
- toString() + source.subSequence(sourceStart, sourceEnd) +
- destination.subSequence(
- destinationEnd, destination.length()).toString();
- Matcher matcher = mPattern.matcher(textToCheck);
- // Entered text does not match the pattern
- if(!matcher.matches()){
- // It does not match partially too
- if(!matcher.hitEnd()){
- return "";
- }
- }
- return null;
- }
- }
The trick is that if the input text does not match the pattern it can match it partially.
If so we will allow the text pasting.
And finally formatting a phone number:
- final String regex = "\\(\\d{3}\\)\\d{3}\\-\\d{2}\\-\\d{2}";
- txt.setFilters(
- new InputFilter[] {
- new PartialRegexInputFilter(regex)
- }
- );
- txt.addTextChangedListener(
- new TextWatcher(){
- @Override
- public void afterTextChanged(Editable s) {
- String value = s.toString();
- if(value.matches(regex))
- txt.setTextColor(Color.BLACK);
- else
- txt.setTextColor(Color.RED);
- }
- @Override
- public void beforeTextChanged(CharSequence s, int start,
- int count, int after) {}
- @Override
- public void onTextChanged(CharSequence s, int start,
- int before, int count) {}
- }
- );
We have:
0 0
- android 格式化输入控制
- android输入金额格式化文本框金额格式控制
- android输入金额格式化文本框金额格式控制
- 解决格式化字符输入的困扰--Android
- 解决格式化字符输入的困扰--Android
- Android 中 EditText 的十六进制格式化输入
- android edittext InputFilter 输入控制
- Android 输入控制和Button
- iOS 数字格式化(手机号码 银行卡号 格式化,验证码输入控制)
- android输入框EditText输入银行卡,输入手机,输入身份证格式化的实现
- android EditText控制最大输入行数
- android的edittext输入内容控制问题
- android EditText控制最大输入行数
- Android EditText输入中英文字数控制
- Android EditText控制内容允许/禁止输入
- Android开发输金额EditText输入控制
- Android 系列 2.12使用KeyListener控制输入
- Android EditText 控制不能输入空格
- 精简Linux文件路径
- 答一名总是半途而废的大二学生:如何坚持,坚持什么
- First Missing Positive
- Java基础知识总结(超级经典)
- 使用eclipse WTP内置的Web Services Explorer测试SOAP based Web Services
- android 格式化输入控制
- Introdution to 3D Game Programming With DirectX11 第12章 习题解答
- Introdution to 3D Game Programming With DirectX11 第13章 习题解答
- Introdution to 3D Game Programming With DirectX11 第14章 习题解答
- Introdution to 3D Game Programming With DirectX11 第15章 习题解答
- MIT differential equation---2
- 小议编程
- 23.喝
- 给一个运行在windows 7和NAT下的VMWARE虚拟机分配固定IP