Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify the number of characters in edit text in android

I have a small trick on how to restrict the number of characters in an edit text in android..for example I want to put a limit say 10 characters for the name field, so it will not allow the user to enter more than 10 characters.

Also, I have another problem in specifying the inputtype for text, I know the procedure which is android:inputType="text|textPersonName" but it dosen't work since it allows the user to enter characters, numbers and also special characters.

I will much appreciate your help.

Thanks in advance

like image 582
ZiZo Avatar asked Jan 31 '26 08:01

ZiZo


2 Answers

Use following xml attributes to set maximum characters and digits to allow

android:digits
android:maxLength

For ex:

<EditText
android:id="@+id/et_name"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:digits="abcdefghijklmnopqrstuvwxyz ."
android:maxLength="10" />

Here, This allows only lower case alphabets, space and dot (.)

Upate

set filter by java

InputFilter myFilter = new InputFilter() { 
        public CharSequence filter(CharSequence source, int start, int end, 
Spanned dest, int dstart, int dend) { 
                for (int i = start; i < end; i++) { 


                        if (!Character.isLetter(source.charAt(i))) { 
                                return ""; 
                        } 

                        if (i == start) {
                           return source.toUpperCase();
                        }

                } 
                return source; 
        } 
}; 

edit.setFilters(new InputFilter[]{myFilter}); 
like image 190
Jayabal Avatar answered Feb 02 '26 00:02

Jayabal


android:maxLength="10"

This worked for me.

like image 44
Harish Rana Avatar answered Feb 02 '26 01:02

Harish Rana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!