skip to Main Content

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


  1. 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 the EditText to the new value but without the last character.

    I’ve tried that for Enter (new line).

    Login or Signup to reply.
  2. Try this

        editText_hex.addTextChangedListener(new TextWatcher() {
    
            public void onTextChanged(CharSequence s, int start, int before, int count) {
    
            }
    
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
            }
    
            public void afterTextChanged(Editable s) {
                if(Pattern.compile("[^0-9A-Fa-f]").matcher(s).find()) {
                    String s2 = s.toString().replaceAll("[^0-9A-Fa-f]", "");
                    editText_hex.setText(s2);
                    editText_hex.setSelection(s2.length());
                }
            }
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search