LoginSignup
12
15

More than 5 years have passed since last update.

EditText で絵文字の入力をさせなくする

Posted at

はじめに

ユーザが自由にテキストを入力できる EditText では、絵文字の入力を防ぎたい場合があります。OS として emoji がサポートされたのって、 KitKat からでしたっけ?

まぁ、とにかく emoji を入力してほしくない時のサンプルです。

サンプルコード

InputFilter inputFilter = new InputFilter {

  public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int send) {
        // 2バイト以上の文字かどうかを判断
        if (source.length() == 0) {
            return source;
        }
        // 入力された1文字が2バイト以上の物について、絵文字かどうか判断をする。
        // UTF-8 の絵文字の文字コードについては、 Wikipedia を参照した
        // https://en.wikipedia.org/wiki/Emoji#Unicode_blocks
        final int codePoint = Character.codePointAt(source, 0);
        if (
                (codePoint >= 0x1F300 && codePoint <= 0x1F5FF ) ||
                (codePoint >= 0x1F900 && codePoint <= 0x1F9FF ) ||
                (codePoint >= 0x1F600 && codePoint <= 0x1F64F ) ||
                (codePoint >= 0x1F680 && codePoint <= 0x1F6FF ) ||
                (codePoint >= 0x2600 && codePoint <= 0x26FF ) ||
                (codePoint >= 0x2700 && codePoint <= 0x27BF )
                ){
            return "";
        }
        return source;
  }
}

コードの話

Wikipediaの記事を参考に、 emoji として利用されている文字の文字コードと入力された文字のそれを地味に比較してる。Unicode8.0で追加された物についても対応をしているので、 Marshmallow の人も大丈夫。

12
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
15