android EditText限制输入框只能输入某些特殊字符、汉字、数字、英文字母等
方法一:在EditText里面设置属性digits,其内容为可以输入的符号,其他的符号不可输入(不能设置中文)
<EditText
android:id="@+id/editMoneyValue"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:digits="12435643asdlfj"
/>
方法二:正则表达式
class RegexFilter(private val regex:Regex, private val max:Int):InputFilter{
override fun filter(source:CharSequence, start:Int, end:Int, dest:Spanned, dstart:Int,
dend:Int):CharSequence? {
if (source.any { !(it =='.' ||it in '0'..'9')}) {
return null
}
val keep =min(max - (dest.length - (dend -dstart)), end -start)
val result = StringBuilder(dest).replace(dstart, dend, source.substring(start, start +max(keep, 0)))
return when {
keep <=0 ->""
dest.isEmpty() &&source.toString() =="." ->"0."
else -> {
when {
regex.matches(result) ->null
else ->dest.subSequence(dstart, dend)
}
}
}
}
}
调用方式:
editDebtValue.filters = arrayOf(RegexFilter("[\\d]{0,12}?(\\.[\\d]{0,2}?)?".toRegex(),15))
效果:只能输入两位小数和12位整数
方法三:自定义筛选器
/**
* 默认可以输入字母、汉字、数字以及()()..·等符号,s为筛选条件
*/classOppositePersonalFilter(vals : String ="[a-zA-Z|\u4e00-\u9fa5()()..·]+") : InputFilter{overridefunfilter(source:CharSequence?, start:Int, end:Int, dest:Spanned?, dstart:Int, dend:Int): CharSequence? {valp = Pattern.compile(s)valm = p.matcher(source.toString())for(iinstart until end) {valcharGet = source?.get(i)if(!Character.isLetterOrDigit(charGet!!) && !m.matches() ) {return""} }returnnull}}
调用方式:
editMoneyValue.apply {
filters = arrayOf(OppositePersonalFilter(), InputFilter.LengthFilter(50))
}
效果:只能输入中文、英文和几个设定的特殊字符----()()..·,相当于白名单,也可以转换筛选条件(if (!Character.isLetterOrDigit(charGet!!)&& !m.matches() ) )达到黑名单效果。
网友评论