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

后端 未结 20 1183
慢半拍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:09

    I have done something like this to keep it simple:

    edit_text.filters = arrayOf(object : InputFilter {
        override fun filter(
            source: CharSequence?,
            start: Int,
            end: Int,
            dest: Spanned?,
            dstart: Int,
            dend: Int
        ): CharSequence? {
            return source?.subSequence(start, end)
                ?.replace(Regex("[^A-Za-z0-9 ]"), "")
        }
    })
    

    This way we are replacing all the unwanted characters in the new part of the source string with an empty string.

    The edit_text variable is the EditText object we are referring to.

    The code is written in kotlin.

提交回复
热议问题