随笔 - 244  文章 - 0  评论 - 11  阅读 - 49万

EditText设置只允许输入文字、拼音、数字

给EditText添加上监听,根据自己的需求,在相应的监听上写上相应的功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
tv_editText = findViewById(R.id.tv_editText);
        tv_editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
 
            }
 
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String edit = tv_editText.getText().toString();
                String str = stringFilter(edit.toString());
                if (!edit.equals(str)) {
                    tv_editText.setText(str);
                    //设置新的光标所在位置
                    tv_editText.setSelection(str.length());
                }
 
            }
 
            @Override
            public void afterTextChanged(Editable editable) {
 
            }
        });

  通过正则表达式来判断,设置只允许输入文字、拼音、数字

1
2
3
4
5
6
7
public static String stringFilter(String str) throws PatternSyntaxException {
        // 只允许字母、数字和汉字其余的还可以随时添加比如下划线什么的,但是注意引文符号和中文符号区别
        String regEx = "[^a-zA-Z0-9\u4E00-\u9FA5]";//正则表达式
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

  

posted on   巫山老妖  阅读(366)  评论(0编辑  收藏  举报
编辑推荐:
· 使用 .NET Core 实现一个自定义日志记录器
· [杂谈]如何选择:Session 还是 JWT?
· 硬盘空间消失之谜:Linux 服务器存储排查与优化全过程
· JavaScript是按顺序执行的吗?聊聊JavaScript中的变量提升
· [杂谈]后台日志该怎么打印
阅读排行:
· 2000 Star,是时候为我的开源项目更新下功能了
· 面试官:DNS解析都整不明白,敢说你懂网络?我:嘤嘤嘤!
· [WPF UI] 为 AvalonDock 制作一套 Fluent UI 主题
· 基于.NET WinForm开发的一款硬件及协议通讯工具
· 内网穿透之http代理服务器
历史上的今天:
2016-09-06 Android中ViewPager如何设置不能通过屏幕左右滑动来切换页面
< 2024年12月 >
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 1 2 3 4
5 6 7 8 9 10 11

点击右上角即可分享
微信分享提示