How to limit characters?

7

I would like to know how to limit characters and then run something on Android.

For example, in a EditText or a TextView I type 5 characters, typing the fifth character executes a command, for example, it deletes what was typed.

    
asked by anonymous 28.01.2015 / 18:16

2 answers

6

To do something at the time anything is typed in EditText, add a TextChangedListener to that EditText

editText.addTextChangedListener(new TextWatcher() {

   @Override
   public void afterTextChanged(Editable s) {

      if(s.length() == 5){
        editText.setText("");//Apaga o conteudo
        //Aqui faça o que pretende ou chame um método da sua Activity
      }
   }

   @Override    
   public void beforeTextChanged(CharSequence s, int start,
     int count, int after) {
   }

   @Override    
   public void onTextChanged(CharSequence s, int start,
     int before, int count) {

   }
  });
    
28.01.2015 / 19:03
7

You can limit either the android:maxLength property in the layout XML or by adding a InputFilter to TextView / EditText .

Examples:

XML

<TextView
        ...
        android:maxLength="5" />

Code

TextView textView = (TextView)findViewById(R.id.id_do_textview);
textView.setFilters( new InputFilter[] { new InputFilter.LengthFilter(5) } );
    
28.01.2015 / 18:24