Ahmed Abdeen
Ahmed Abdeen

Reputation: 356

How can I force user to enter emoji only in edittext

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"/>

Upvotes: 1

Views: 998

Answers (1)

Nik
Nik

Reputation: 2060

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;
            }
        }
    }

Upvotes: 1

Related Questions