关于EditText屏蔽Emoji表情及屏蔽其它非法字符带来的光标不准确问题

本文介绍了一种在Android应用中使用的EditText组件上屏蔽Emoji表情的方法。通过对EditText的addTextChangedListener监听器进行定制,实现了有效拦截Emoji表情输入的功能,并保持了光标的正确位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


最近的项目使用了EditText编辑文本,但需要屏蔽Emoji表情,于是在EditText的addTextChangedListener做了以下操作

    private String before = "";
    int couIndex;
    boolean isAutoSet;

   mTxtReplay.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (!isAutoSet) {//判断是手动编辑录入还是通过setText自动设置的  如果是setText设置,则start为0,不再改变光标位置
                    couIndex = start;//记录最后一次光标所在位置
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                before = s.toString();
            }

            @Override
            public void afterTextChanged(Editable s) {

                if (isEmoji(mTxtReplay.getText().toString()) || mTxtReplay.getText().toString().contains("☺")) {//判断Emoje表情
                    isAutoSet = true;
                    mTxtReplay.setText(before); //setText的时候会调用onTextChanged并重置start位置为0,所以需要
                    isAutoSet = false;
                    mTxtReplay.setSelection(couIndex);//将最后一次输入文本的开始位置再设置到光标位置
                }
                if (mTxtReplay.getText().toString().length() > 1000) {
                    mTxtReplay.setText(before);
                    ToastUtil.showToast(CarOwnerQuestionReplayActivity.this, "最多输入1000字");
                }

            }
        });

/**
     * 判断方便是否是Emoji表情
     * @param string
     * @return
     */
    public boolean isEmoji(String string) {
        Pattern p = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(string);
        return m.find();
    }










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值