How to write InputFilter to restrict EditText input to HEX numbers? I need to restrict all characters except 0123456789abcdefABCDEF
android:digits doesn`t work anymore after I increased target api from 29 to 30:
android:digits="0123456789abcdefABCDEF"
android:inputType="text|textNoSuggestions"
Here is my XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/hex_linear_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/editText_hex"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimaryLight"
android:digits="0123456789abcdefABCDEF"
android:inputType="text|textNoSuggestions"
android:gravity="center"
android:importantForAutofill="no"
android:maxLength="6"
android:maxLines="1"
android:textAlignment="center"
android:textColor="@android:color/black"
android:textSize="24sp"
tools:ignore="LabelFor" />
</LinearLayout>
Attempt
I can ignore unwanted characters using:
if (editText_hex.getText().toString().matches("[0-9a-fA-F]{6}")){
...
}
But I want to restrict input (not ignore)
2
Answers
There is a complicated way to do it, but not sure how effective it is.
You can use a
TextWatcher
to see what new letters are being typed. If the letter is something you don’t want, you just set the text of theEditText
to the new value but without the last character.I’ve tried that for Enter (new line).
Try this