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

后端 未结 25 1792
你的背包
你的背包 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:28

    Here's my take on Pratik Sharma's answer for Kotlin and Double if any one needs it

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

提交回复
热议问题