Run something after inserting a certain number of characters in an Edittext?

Asked

Viewed 6,768 times

8

I wonder how to limit characters and run something then on Android.

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

2 answers

8

You can limit through the property android:maxLength in the XML layout or by adding a InputFilter in the 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) } );
  • @Rodolfo I don’t understand your question.

  • @Rodolfo I just missed the "run something next" part of your question! Take a look at the ramaral answer.

  • this is the one that should be correct. No unnecessary processing.

7


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) {

   }
  });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.