Often you might want to limit the number of characters a user can enter into your EditText control in Android. There are two ways to accomplish this:
- Using XML (e.g. layout or style)
- By code
1. Using XML:
Add android:maxLength property to the EditText definition in the XML file (or the style sheet). For example, to limit the text of EditText to 10 characters at most:
[sourcecode language="xml" light="true"]
<EditText android:id="@id+/txtFixedLength" android:maxLength="10" />
[/sourcecode]
2. By code:
Unfortunately, Android does not have a setMaxLength
method to easily set the maximum length for a text input by code. To achieve this, we have to use InputFilters
. The following example demonstrates achieving the same task as before (i.e. limiting the word length to at most 10 characters) in code:
[sourcecode language="java"]
// Load the EditText from layout
EditText txtFixedLength = (EditText) findViewById(R.id.txtFixedLengthInput);
// Create a new InputFilter to define the maximum length
InputFilter maxLengthFilter = new InputFilter.LengthFilter(10);
// Apply the filter to the EditText. The array can contain other filters.
txtFixedLength.setFilters(new InputFilter[]{ maxLengthFilter });
[/sourcecode]