我正在开发一个键盘应用程序,但出现了问题。我想通过编程的方式在Android EditText中限制/阻止软键盘输入一些特殊字符。所以,请问有没有办法实现这个功能?
很遗憾,接受的解决方案并不适用于所有情况。正确的解决方案是使用以下InputFilter
:
private InputFilter filter = new InputFilter() {
// An example pattern that restricts the input only to the lowercase letters
private static final Pattern restrictedChars = Pattern.compile("[a-z]*")
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
final CharSequence replacementText = source.subSequence(start, end);
final CharSequence replacedText = dest.subSequence(dstart, dend);
if (source == null || restrictedChars.matcher(replacementText).matches()) {
return null; // Accept the original replacement
}
return replacedText; // Keep the original text
}
};
class NameActivity : AppCompatActivity() {
var myFilter = InputFilter { source, _, _, _, _, _ ->
try {
val c = source[0]
return@InputFilter if (Character.isLetterOrDigit(c) || c == '_' || c == '.' || c == ' ')
c.toString()
else
""
} catch (e: Exception) { }
null
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_name)
val edittext = findViewById<EditText>(R.id.edittext)
edittext.filters = (arrayOf(myFilter))
}
}
这对我来说是有效的...
android:digits="÷×=%_-+#().,abcdefghijklmnopqrstuvwxyzA BCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\n\u0020"
用于空格的代码:
\u0020
换行请使用:
\n
使用以下选项进行输入法设置:
android:singleLine="true"
android:maxLines="1"
val regex = Regex("^[~#^|$%&*!]*$")
val filter = InputFilter { source, _, _, _, _, _ ->
return@InputFilter when {
source?.matches(regex) == true -> ""
else -> null
}
}
editText.filters = arrayOf(filter)
对于处理复制-粘贴
文本的情况,可以通过添加条件来检查输入的文本是否大于1
来完成,现在的代码如下:
val regex = Regex("^[~#^|$%&*!]*$")
val filter = InputFilter { source, _, _, _, _, _ ->
return@InputFilter when {
source?.matches(regex) == true -> ""
source.length > 1 -> source.trim { it.toString().matches(regex) } // Put your desired logic here, these sample logic was doing a trim/remove
else -> null
}
}
editText.filters = arrayOf(filter)
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:digits="abcdefghijklmnopqrstuvwxyzA BCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\n\u0020"
android:singleLine="true"
android:textColor="@color/black" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:digits=".,?:/abcdefghijklmnopqrstuvwxyzA BCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\n\u0020"
android:singleLine="false"
android:textColor="@color/black" />