How do I use InputFilter to limit characters in an EditText in Android?

后端 未结 20 1126
慢半拍i
慢半拍i 2020-11-22 04:23

I want to restrict the chars to 0-9, a-z, A-Z and spacebar only. Setting inputtype I can limit to digits but I cannot figure out the ways of Inputfilter looking through the

20条回答
  •  一向
    一向 (楼主)
    2020-11-22 05:11

    First add into strings.xml:

    0123456789abcdefghjklmnprstuvwxyz
    

    XML:

    android:digits="@string/vin_code_mask"
    

    Code in Kotlin:

    edit_text.filters += InputFilter { source, start, end, _, _, _ ->
        val mask = getString(R.string.vin_code_mask)
        for (i in start until end) {
            if (!mask.contains(source[i])) {
                return@InputFilter ""
            }
        }
        null
    }
    

    Strange, but it works weirdly on emulator's soft keyboard.

    Warning! The following code will filter all letters and other symbols except digits for software keyboards. Only digital keyboard will appear on smartphones.

    edit_text.keyListener = DigitsKeyListener.getInstance(context.getString(R.string.vin_code_mask))
    

    I also usually set maxLength, filters, inputType.

提交回复
热议问题