删除粘贴前的空白,并设置最大长度



所以我使用TextInputEditText,最大长度为8。

如果我粘贴"1234 1234",它会变成"1234 123"。我的目标是让它变成"12341234">

最难的部分是最大长度,因为如果我使用通常的过滤器或onTextChange,它将无法工作,因为在它修剪空白之前首先切割的长度。它将变成"1234123";相反。

所以我想在粘贴到编辑文本之前修剪空白。

你知道吗?

编辑:因为每个评论者都没有读过我的问题。这就是为什么onTextChanged不工作在我的。我复制"1234 1234"。当我粘贴时,由于最大长度,它将被转换为"1234 123"然后转到TextWatcher Listener或RxJava Listener。所以如果我把它放在onTextChange,beforeTextChange或afterTextChange中,它已经变成了&;1234123&;,因此我无法实现&;12341234&;

这是一个InputFilter。长度过滤器应该工作:

private class MyLengthFilter(max: Int) : InputFilter.LengthFilter(max) {
private val mMax = max
override fun filter(
source: CharSequence, start: Int, end: Int, dest: Spanned, dstart: Int, dend: Int
): CharSequence? {
val newSource = super.filter(source, start, end, dest, dstart, dend)
if (newSource.isNullOrEmpty()) return newSource
// Calculate how many characters were truncated
val truncated = (end - start) - newSource.length
if (truncated <= 0) return newSource
// Remove all space characters. Adjust this to change how the replacement string is adjusted.
val noSpaceSource = source.filter { !Character.isSpaceChar(it) }
if (noSpaceSource == source) return newSource // No white space.
return super.filter(
noSpaceSource, start, start + noSpaceSource.length, dest, dstart, dend
) ?: noSpaceSource
}
}

请注意InputFilter中关于span的注释,当sourcespanSpannable的实例时,以防它影响您。

最新更新