Last active
December 12, 2018 03:09
-
-
Save CapnSpellcheck/7c72830e43927380daf5205100c93977 to your computer and use it in GitHub Desktop.
An InputFilter for Android EditText that limits the number of newlines the user can type into it.
This file contains 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
import android.text.InputFilter | |
import android.text.Spanned | |
class NewlineLimitingInputFilter(val maxLines: Int) : InputFilter { | |
var monitor: LimitMonitor? = null | |
var numNewlines = 0 | |
override fun filter(source: CharSequence, start: Int, end: Int, dest: Spanned, dstart: Int, dend: Int): CharSequence? { | |
// subtract all newlines in dest range | |
for (char in dest.subSequence(dstart, dend)) { | |
if (char == '\n') { | |
numNewlines-- | |
} | |
} | |
var replacement: StringBuilder? = null | |
// add newlines in source | |
var char: Char | |
for (i in start until end) { | |
char = source[i] | |
if (replacement != null) { | |
if (char != '\n') | |
replacement.append(char) | |
else if (numNewlines >= maxLines) | |
monitor?.onLimitExceeded(this) | |
else | |
numNewlines++ | |
} | |
else if (char == '\n') { | |
if (numNewlines >= maxLines) { | |
monitor?.onLimitExceeded(this) | |
replacement = StringBuilder(source.subSequence(start, i)) | |
} | |
else | |
numNewlines++ | |
} | |
} | |
return replacement | |
} | |
interface LimitMonitor { | |
fun onLimitExceeded(filter: InputFilter) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment