Skip to content

Instantly share code, notes, and snippets.

@CapnSpellcheck
Last active December 12, 2018 03:09
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
An InputFilter for Android EditText that limits the number of newlines the user can type into it.
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