srk
srk

Reputation: 435

How to limit the number of characters entered by a user in EditText in Android?

I want the user to enter only one character in the EditText field.So, if he tries to enter a string the program should not allow it and limit it to only one character.How can i achieve it? Thanks

Upvotes: 2

Views: 1190

Answers (2)

bongo
bongo

Reputation: 763

from layout add attribute

android:maxLength="1"

or from code

TextEdit te = findViewById(...);
te.setFilters( new InputFilter[] { new InputFilter.LengthFilter(1) } )

Upvotes: 6

Pavel Dudka
Pavel Dudka

Reputation: 20944

There is a maxLength attribute in EditText. Just set it to 1:

<EditText 
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:maxLength="1"/>

Upvotes: 3

Related Questions