2011-11-22 18 views

Respuesta

30

Tienes que addTextChangedListener a su EditText

De esta manera:

yourEditText.addTextChangedListener(new TextWatcher() { 
     @Override 
     public void afterTextChanged(Editable arg0) { 
     enableSubmitIfReady(); 
     } 

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

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

En ese método, que debe hacer la siguiente manera:

public void enableSubmitIfReady() { 

    boolean isReady = yourEditText.getText().toString().length() > 3;  
    yourbutton.setEnabled(isReady); 
    } 

espero que ayude.

+1

Creo enableSubmitIfReady() debe estar en OnTextChanged – rohit

+2

Buena respuesta, excepto Yo prefiero ver ese tipo de if-else modelo simplificado en: ' yourbutton.setEnabled (isReady); ' – mharper

+0

¿Cómo funciona esto sin hacer referencia al botón? Usted tiene la línea yourbutton ... pero su botón no tiene referencia en ningún lugar de este código, entonces, ¿cómo puede funcionar? –

1

El problema con el uso de afterTextChanged solo es que al inicio de la aplicación no se puede desactivar el botón inicialmente hasta que empiece a escribir en EditText.

Así es como implementé el mío y funciona muy bien. Llamar a este método dentro de su método onCreate Actividad

void watcher(final EditText message_body,final Button Send) 
{ 
    final TextView txt = (TextView) findViewById(R.id.txtCounter); 
    message_body.addTextChangedListener(new TextWatcher() 
    { 
     public void afterTextChanged(Editable s) 
     { 
      txt.setText(message_body.length() + "/160"); //This is my textwatcher to update character left in my EditText 
      if(message_body.length() == 0) 
       Send.setEnabled(false); //disable send button if no text entered 
      else 
       Send.setEnabled(true); //otherwise enable 

     } 
     public void beforeTextChanged(CharSequence s, int start, int count, int after){ 
     } 
     public void onTextChanged(CharSequence s, int start, int before, int count){ 
     } 
    }); 
    if(message_body.length() == 0) Send.setEnabled(false);//disable at app start 
} 
1

Puede hacer lo que dice, sino @Udaykiran utilizar arg0.length() lugar.

El Editable también contiene la longitud del contenido de la TextEditor que se ha cambiado

Cuestiones relacionadas