Android EditText输入框限制输入表情,限制输入长度

自定义输入框Java代码

public class ForbidEmojiEditText extends android.support.v7.widget.AppCompatEditText {

    /**
     * 最大输入长度
     */
    private int mShowMaxLength;

    private static final int MAX_LENGTH = 5;

    public ForbidEmojiEditText(Context context) {
        super(context);
    }

    public ForbidEmojiEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        mShowMaxLength = MAX_LENGTH;
        if (attrs != null) {
            TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.ForbidEmojiEditText);
            mShowMaxLength = arr.getInt(R.styleable.ForbidEmojiEditText_edtShowMaxLength, MAX_LENGTH);
            arr.recycle();
        }
        setFilters();
    }

    public ForbidEmojiEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mShowMaxLength = MAX_LENGTH;
        if (attrs != null) {
            TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.ForbidEmojiEditText);
            mShowMaxLength = arr.getInt(R.styleable.ForbidEmojiEditText_edtShowMaxLength, MAX_LENGTH);
            arr.recycle();
        }
        setFilters();
    }

    public void setFilters() {
        InputFilter emojiFilter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
                                       int dstart, int dend) {
                Pattern emoji = Pattern.compile(
                        "[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                        Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
                Matcher emojiMatcher = emoji.matcher(source);
                if (emojiMatcher.find()) {
                    return "";
                }
                return null;
            }
        };
        super.setFilters(new InputFilter[]{emojiFilter, new InputFilter.LengthFilter(mShowMaxLength)});
    }
}

attrs.xml

<declare-styleable name="ForbidEmojiEditText">
    <attr name="edtShowMaxLength" format="integer"/>
</declare-styleable>

view

xmlns:app="http://schemas.android.com/apk/res-auto">
<com.***.ForbidEmojiEditText
        android:layout_width="match_parent"
        android:layout_height="@dimen/dimen_50_dp"
        android:background="@null"
        android:textColor="@color/gray"
        android:textColorHint="@color/line_border"
        android:textSize="@dimen/text_size_small"
        app:edtShowMaxLength = "20"/>

ok,剩下的工作就是把它像EditText一样去应用吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值