Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EditText : set number of characters programmatically

I have a EditText , and I would like to restrict the number of characters which could be inputted in this EditText, and make this restriction programmatically, how to do it? For example, say I would like to restrict it to only allow 10 characters.

like image 729
john123 Avatar asked Nov 16 '12 10:11

john123


People also ask

How to set minimum and maximum input value in edittext in android?

setFilters(new InputFilter[]{ new InputFilterMinMax("1", "12")}); This will allow user to enter values from 1 to 12 only. EDIT : Set your edittext with android:inputType="number" .

How to count number of characters in edittext while typing in Android?

This example demonstrates how do I count number of characters in editText while typing in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. Step 3 − Add the following code to src/MainActivity.java

What is edittext in Android?

In Android, EditText is a subclass of TextView which is configured to be editable. EditText is used for giving textual input such as characters, strings, numbers, etc. It has no limitation on the type of input unless explicitly attributed.

Can edittext accept only a string or a number?

It has no limitation on the type of input unless explicitly attributed. Meaning we can attribute the EditText to accept only a string or a number. On top of this, we can create methods to accept only a certain type of value to facilitate the desired task.

How many input types can be displayed in the edittext?

You can see that if we try to give an input between 1-100, we are able to see it typed in the EditText. However, if we try to give 0 or something above 100, the input is not accepted and therefore not seen displayed or typed in the EditText.


2 Answers

You can Use InputFilter for restricting the number of characters in EditView programmatically as:

InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(10);
your_edittext.setFilters(FilterArray);

for more help you can see this tutorial for restricting number of characters in EditView:

http://www.tutorialforandroid.com/2009/02/maxlength-in-edittext-using-codes.html

like image 63
ρяσѕρєя K Avatar answered Oct 02 '22 19:10

ρяσѕρєя K


I would implement a filter:

InputFilter filter = new InputFilter() {

   @Override
   public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
      if (source.length > 10){
       //cancel the edit or whatever
      }
   }
};
EditText editText = (EditText) findViewById(R.id.rg);
editText.setFilters(new InputFilter[] {filter});
like image 30
Shine Avatar answered Oct 02 '22 19:10

Shine