3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Android】EditTextに指定文字のみ入力+文字数制限を行う

Last updated at Posted at 2020-10-07

1. 指定文字のみ入力するフィルターをクラスで作成

例として、カタカナのみ入力できるようにする

    class KatakanaInputFilter : InputFilter {
       override fun filter(source: CharSequence, start: Int, end: Int, dest: Spanned, dstart: Int, dend: Int) =
             "[^ァ-ヶ]".toRegex().replace(source, "")
    }

2. フィルターのセット

フィルターセット時、配列になっているので、ここで指定文字のみ入力+文字数制限のフィルターをセットする

    edit_text.filters = arrayOf(KatakanaInputFilter(), InputFilter.LengthFilter(30))

追記

以下の方法だと、余分なクラスを作らない + xmlでandroid:maxLengthを指定しても反映されるようになる。

val filter = InputFilter { source, _, _, _, _, _ ->
	if (source.matches("^[ァ-ヶ]+$".toRegex())) source else ""
}

if (filter !in edit_text.filters) edit_text.filters = arrayOf(*edit_text.filters, filter)

カタカナのみ:ァ-ヶ
絵文字のみ:\uD800-\uDBFF\uDC00-\uDFFF
半角のみ(半角カナ含む):\x01-\x7E\uFF61-\uFF9F

3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?