How can I force user to enter emoji only in edittext

倾然丶 夕夏残阳落幕 提交于 2020-12-07 07:44:53

问题


I'm using androidx.emoji.widget.EmojiEditText. I want to force user to enter only emojis here. And limit him to max 3 emojis. How can I do something like this? I tried to use external emoji keyboard that cancels the soft keyboard and shows up but didn't work properly.

<androidx.emoji.widget.EmojiEditText
                            android:id="@+id/etEmoji"
                            android:layout_width="match_parent"
                            android:layout_height="30dp"
                            android:layout_margin="10dp"
                            android:hint="Enter Emoji"
                            android:inputType="textShortMessage"
                            android:background="@android:color/transparent"/>

回答1:


Below class will only allow Emojis and symbols.

public class CustomEditText extends EditText {
        public CustomEditText(Context context) {
            super(context);
            init();
        }

        public CustomEditText(Context context, AttributeSet attrs) {
            super(context, attrs);
            init();
        }

        public CustomEditText(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            init();
        }

        private void init() {
            setFilters(new InputFilter[]{new EmojiIncludeFilter()});
        }

        private class EmojiIncludeFilter implements InputFilter {

            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                for (int i = start; i < end; i++) {
                    int type = Character.getType(source.charAt(i));
                    if (type != Character.SURROGATE && type != Character.OTHER_SYMBOL) {
                        // Other then emoji value will be blank
                        return "";
                    }
                }
                return null;
            }
        }
    }


来源:https://stackoverflow.com/questions/57865125/how-can-i-force-user-to-enter-emoji-only-in-edittext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!