Last active
November 28, 2017 06:52
-
-
Save hilfritz/0e36bfb150dcb315d0be680560300b05 to your computer and use it in GitHub Desktop.
Limit the inputs the edittext will receive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Usage: | |
| * val limit0to24 = EditTextInputFilter(0, 23) | |
| * val limitChars = EditTextInputFilter(arrayListOf("a","b","c","d","e","f","g","h", "ab", "cd")) | |
| * input1.setFilters(arrayOf(limit0to24)) | |
| * input2.setFilters(arrayOf(limitChars)) | |
| * | |
| */ | |
| class EditTextInputFilter : InputFilter { | |
| private var min: Int = 0 | |
| private var max: Int = 0 | |
| private var list: ArrayList<String> = ArrayList() | |
| var view: View? = null | |
| 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) | |
| } | |
| constructor(list: ArrayList<String>) { | |
| this.list = list | |
| } | |
| override fun filter(source: CharSequence, start: Int, end: Int, dest: Spanned, dstart: Int, dend: Int): CharSequence? { | |
| try { | |
| if (isNumeric()) { | |
| val input = Integer.parseInt(dest.toString() + source.toString()) | |
| if (isInRange(min, max, input)) { | |
| return null | |
| } | |
| }else if (isCharacters()){ | |
| val input = dest.toString() + source.toString() | |
| if (list.contains(input)) { | |
| return null | |
| } | |
| } | |
| } catch (e: Exception) { | |
| } | |
| return "" | |
| } | |
| private fun isInRange(a: Int, b: Int, c: Int): Boolean { | |
| return if (b > a) c >= a && c <= b else c >= b && c <= a | |
| } | |
| private fun isNumeric():kotlin.Boolean{ | |
| var retVal = false | |
| retVal = !(min==0 && max==0) | |
| return retVal | |
| } | |
| private fun isCharacters():kotlin.Boolean{ | |
| var retVal = false | |
| list?.let{ | |
| if (list.size>0) | |
| retVal = true | |
| } | |
| return retVal | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment