I have a EditText
field, variable name valueInputField
.
I listen to the text input change, what I want to achieve is during inputting, when the input format DOESN'T matches a regular expression, I would like to stop showing more inputs, but keep the field focused & user is able to type on keyboard still just that no real effect will take to the field.
@OnTextChanged(R.id.value_input)
protected void onTextChanged(CharSequence charSequence) {
String inputChars = charSequence.toString().trim();
// if doesn't match regular expression, stop showing more inputs
if (!inputChars.matches(MY_REGEXP)) {
// this doesn't achieve what I need.
valueInputField.setInputType(0)
}
}
I tried above way, it doesn't work. How to achieve what I need?
The most reliable way to do this is using UI. setReadOnly(myEditText, true) from this library. There are a few properties that have to be set, which you can check out in the source code.
In your xml code set focusable="false" , android:clickable="false" and android:cursorVisible="false" and this will make your EditText treat like non editable.
maybe you should try below logic
maxLength=inputChars.length
if (!inputChars.matches(MY_REGEXP)) {
editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});
}
above program will set a max length of EditText when it does not match regexp.
You have to add an InputFilter to your textView:
here's an example:
editText.filters = arrayOf(object: InputFilter {
override fun filter(source: CharSequence?, start: Int, end: Int, dest: Spanned?, dstart: Int, dend: Int): CharSequence {
if (Regex("[0-9]*").matches(source!!)) {
return source
} else {
return source.subSequence(start, end-1)
}
}
})
This filter method gets called everytime the input in the editText is being invoked. You can return the source when it matches a regex, otherwise, you can return a subSequence of the source, without the last char inserted.
The code example is in Kotlin, the translation shouldn't give you any problem :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With