Skip to content

Instantly share code, notes, and snippets.

@mvasilova
Created December 9, 2019 08:15
Show Gist options
  • Save mvasilova/6273e0c87ff109fa732cef6cbab46efe to your computer and use it in GitHub Desktop.
Save mvasilova/6273e0c87ff109fa732cef6cbab46efe to your computer and use it in GitHub Desktop.
InputFilter min, max for EditText
import android.text.InputFilter
import android.text.Spanned
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
}
}
//Usages
editText.filters = arrayOf<InputFilter>(InputFilterMinMax("1", "300"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment