From 448c722023ba1740105fc92f485fd4843c1774a9 Mon Sep 17 00:00:00 2001 From: Ztiany Date: Tue, 12 Nov 2019 21:07:02 +0800 Subject: [PATCH] update TextViewEx --- .../base/utils/android/views/TextViewEx.kt | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/lib_base/src/main/java/com/android/base/utils/android/views/TextViewEx.kt b/lib_base/src/main/java/com/android/base/utils/android/views/TextViewEx.kt index f0693ce..f2cd68e 100644 --- a/lib_base/src/main/java/com/android/base/utils/android/views/TextViewEx.kt +++ b/lib_base/src/main/java/com/android/base/utils/android/views/TextViewEx.kt @@ -10,6 +10,7 @@ import androidx.annotation.DrawableRes import androidx.core.content.ContextCompat import com.android.base.interfaces.TextWatcherAdapter import com.google.android.material.textfield.TextInputLayout +import java.util.regex.Pattern inline fun TextView.textWatcher(init: KTextWatcher.() -> Unit) = addTextChangedListener(KTextWatcher().apply(init)) @@ -162,6 +163,34 @@ fun EditText.disableEmojiEntering() { filters = newFilters } + +fun EditText.disableEntering(regex: String) { + val filter = RegexOnlyFilter(regex) + val oldFilters = filters + val oldFiltersLength = oldFilters.size + val newFilters = arrayOfNulls(oldFiltersLength + 1) + if (oldFiltersLength > 0) { + System.arraycopy(oldFilters, 0, newFilters, 0, oldFiltersLength) + } + //添加新的过滤规则 + newFilters[oldFiltersLength] = filter + filters = newFilters +} + +private class RegexOnlyFilter(regex: String) : InputFilter { + + private val pattern: Pattern = Pattern.compile(regex) + + override fun filter(source: CharSequence, start: Int, end: Int, dest: Spanned, dstart: Int, dend: Int): CharSequence? { + val matcher = pattern.matcher(source) + return if (!matcher.find()) { + null + } else { + "" + } + } +} + private class EmojiExcludeFilter : InputFilter { override fun filter(source: CharSequence, start: Int, end: Int, dest: Spanned, dstart: Int, dend: Int): CharSequence? { for (i in start until end) {