Is there a way to define a min and max value for EditText in Android?

后端 未结 25 1623
你的背包
你的背包 2020-11-22 11:51

I want to define a min and max value for an EditText.

For example: if any person tries to enter a month value in it, the value must be between 1-12.

25条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 12:42

    Kotlin if any one needs it (Use Utilities)

    class InputFilterMinMax: InputFilter {
        private var min:Int = 0
        private var max:Int = 0
        constructor(min:Int, max:Int) {
            this.min = min
            this.max = max
        }
        constructor(min:String, max:String) {
            this.min = Integer.parseInt(min)
            this.max = Integer.parseInt(max)
        }
        override fun filter(source:CharSequence, start:Int, end:Int, dest: Spanned, dstart:Int, dend:Int): CharSequence? {
            try
            {
                val input = Integer.parseInt(dest.toString() + source.toString())
                if (isInRange(min, max, input))
                    return null
            }
            catch (nfe:NumberFormatException) {}
            return ""
        }
        private fun isInRange(a:Int, b:Int, c:Int):Boolean {
            return if (b > a) c in a..b else c in b..a
        }
    }
    

    Then use this from your Kotlin class

    percentage_edit_text.filters = arrayOf(Utilities.InputFilterMinMax(1, 100))
    

    This EditText allows from 1 to 100.

    Then use this from your XML

    android:inputType="number"
    

提交回复
热议问题