2012-05-07 9 views
13

Estoy creando una opción de búsqueda en una aplicación de Android.Deshabilitar el botón de enviar del teclado cuando aún no se ha escrito nada [Android]

Después de presionar "Buscar" en el pantalla-teclado se activa un evento que envía la consulta al servidor. Lo que quiero hacer es deshabilitar el botón "Buscar" en el pantalla-teclado cuando aún no se ha escrito texto en su correspondiente EditText.

que añade esto a la EditText:

android:imeOptions="actionSearch"

Por eso es que el teclado tiene un botón "Buscar" en lugar de la opción predeterminada "enter"/"hecho". (Por si acaso te preguntas)

Respuesta

16

No puede desactivar el botón de acción en el teclado androide. Tendrá que conformarse con verificar la cadena vacía en el oyente de acción del editor.

+0

Eso es malo. Supongo que será necesario verificar si hay una cadena vacía. Elegiré esta respuesta porque es la respuesta real a mi pregunta, no solo las alternativas. – Pieter888

-1
SearchInput.addTextChangedListener(new TextWatcher() { 

     @Override 
     public void afterTextChanged(Editable s) { 
      // TODO Auto-generated method stub 
      if(SearchInput.getText().toString().length() == 0) 
      { 
       Search.setClickable(false); 
      } 
     } 

     @Override 
     public void beforeTextChanged(CharSequence s, int start, int count, 
       int after) { 
      // TODO Auto-generated method stub 
      Search.setClickable(false); 


     } 

     @Override 
     public void onTextChanged(CharSequence s, int start, int before, 
       int count) { 
      // TODO Auto-generated method stub 
      Search.setClickable(true); 
     } 

    }); 

o Prueba esto ..! para dilog error de fantasía

Search.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 

      if(searchinput.getText().toString().length() == 0) 
      { 
       searchinput.setError("Enter something Blah Blah..!"); 
      } 
      else 
      { 


     // Original Functions Goes Here 
      } 

utilizar el siguiente código de edición de texto,

android:imeOptions="flagNoEnterAction" 

no soy capaz de establecer flagNoEnterAction = "false" Pero alguien le puede ayudar a

+0

Esto solo funciona si el botón de búsqueda fue un botón que hice en la aplicación. Pero estoy hablando de deshabilitar la tecla enter/search en el teclado android. – Pieter888

+0

No votaré esta respuesta porque no es una respuesta válida a mi pregunta. Quiero desactivar el botón de búsqueda del teclado en pantalla de Android. No hay un botón en mi aplicación – Pieter888

+0

Respuesta editada, tercer código agregado, podría ayudarlo a usted u otra persona al menos – VenomVendor

0

probar esto (puede no ser el resultado exacto que usted quería, pero podría ser lo más cercano que pueda obtener.

1) Retire el androide: imeOptions = "actionSearch" del XML

2) Crear una costumbre TextWatcher addTextChangedListener (TextWatcher observador) que le permite cambiar el teclado dinámicamente algo como esto

textMessage = (EditText)findViewById(R.id.textMessage); 
textMessage.addTextChangedListener(new TextWatcher(){ 
     public void afterTextChanged(Editable s) { 
      if(firstTime){//a boolean you init to true 
      firstTime = false; 
      textMessage.setImeOptions(EditorInfo.IME_ACTION_SEARCH); 
     } 
     public void beforeTextChanged(CharSequence s, int start, int count, int after){} 
     public void onTextChanged(CharSequence s, int start, int before, int count){} 
    }); 
+0

Lo intenté, pero no es posible cambiar el botón 'ImeOptions' después de que se haya creado la vista. Pero no se siente como la solución correcta de todos modos porque quiero que se deshabilite el botón enter/search hasta que se haya tipeado algo. Si esta respuesta funcionara, mostraría el texto "Hecho" en el botón Intro en lugar de "Buscar". Solo quiero que el botón esté en gris o algo que muestre al usuario que no puede, por lo que una búsqueda en una cadena vacía. – Pieter888

0

se necesita hacer Custom EditText, Make Extends EditText y @Override Below Method en él.

Aquí hay un código de ejemplo.

private ArrayList<Integer> keysToIgnore = new ArrayList<Integer>(); 

    public EditTextCus(Context context) { 
     super(context); 
    } 

    public EditTextCus(Context context, AttributeSet attrs){ 
     super(context, attrs);  
    } 

    public EditTextCus(Context context, AttributeSet attrs, int defStyle){ 
     super (context, attrs, defStyle);  
    } 



private Boolean keyInIgnoreList(int keyCode) {  
     for (Integer i:keysToIgnore){ 
      int key = i.intValue(); 
      if (key == keyCode) 
       return true; 
     } 
     return false; 
    } 

    public void addKeyToIgnoreList(int keyCode) { 

     if (!keyInIgnoreList(keyCode)){ 
      keysToIgnore.add(keyCode); 
     } 
    } 

    public void removeKeyFromIgnoreList(int keyCode) { 

     if (keyInIgnoreList(keyCode)){ 
      Integer key=new Integer(keyCode); 
      keysToIgnore.remove(key); 
     } 
    } 


@Override 
    public boolean dispatchKeyEventPreIme(KeyEvent event) { 
     //Log.d("ws", "dispatchKeyEventPreIme(" + event + ")"); 

      // swallow the any key in the ignore list 
      if (keyInIgnoreList(event.getKeyCode())) { 
       KeyEvent.DispatcherState state = getKeyDispatcherState(); 
       if (state != null) { 
        if (event.getAction() == KeyEvent.ACTION_DOWN 
          /*&& event.getRepeatCount() == 0*/) { 
         state.startTracking(event, this); 
         return true; 
        } else if (event.getAction() == KeyEvent.ACTION_UP 
          && !event.isCanceled() && state.isTracking(event)) { 
         return true; 
        } 
       } 
      } 
     } 
     return super.dispatchKeyEventPreIme(event); 
    } 

también se puede hacer esto a la clave de búsqueda:

mCustomEditText.setOnEditorActionListener(new OnEditorActionListener() { 

      public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { 
       if(actionId==EditorInfo.IME_ACTION_SEARCH && event.getAction()==KeyEvent.KEYCODE_SEARCH){ 
        System.out.println("Search pressed........."); 
       } 
       return false; 
      } 
     }); 
+0

Incluso después de agregar tanto el código de tecla de enter (66) como de búsqueda (84), todavía no lo ignora. Después de descomentar la línea donde se registra el evento, descubrí que nunca llega al 'dispatchKeyEventPreIme'. Nada se envía a la consola. – Pieter888

+0

@ Pieter888 cuando la tecla Hard de Buscar como en el teléfono HTC verá 'dispatchKeyEventPreIme' llamará a este método y para recibir el evento de tecla programable puede probar esto' mCustomEditText.setOnEditorActionListener' como se actualizó en la respuesta. Intente en este método para ingresar la clave para softkeyboard . – Herry

0

Implementar OnKeyListener en su Activity.

agregue este keyListener a su EditText.

myEditText.setOnKeyListener(this); 

anulación onKey() en su Activity.

@Override 
    public boolean onKey(View v, int keyCode, KeyEvent event) { 
     if(v.getId() == R.id.myEditText) 
     { 
      if(KeyEvent.KEYCODE_ENTER == keyCode) 
      { 
       if(myEditText.getText().toString().equals("") || myEditText.getText().toString().equals(null)) 
       { 
        Toast.makeText(KeyboardTestActivity.this, "Event Eaten", Toast.LENGTH_SHORT).show(); 
        Log.e("onKey", "Event Eaten"); 
        return true; 
       } 
      } 
     } 
     return false; 
    } 

y esto se hace se mostrará un pan tostado siempre que su EditText está vacío y pulsa la tecla de búsqueda.

Nota: onKey() se llama dos veces una vez para keyDown y luego para KeyUp. tendrá que filtrarlo utilizando la instancia de KeyEvent, recibida como un parámetro en el método onKey().

+0

probé este enfoque. Funciona bien ... –

0

Adjunte OnEditorActionListener a su campo de texto y devuelva verdadero desde su método onEditorAction, cuando actionId es igual a IME_ACTION_DONE. Esto evitará teclado en pantalla de ocultación:

EditText txtEdit = (EditText) findViewById(R.id.txtEdit); 
txtEdit.setOnEditorActionListener(new OnEditorActionListener() { 

    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { 
    if (actionId == EditorInfo.IME_ACTION_DONE) { 
     // your additional processing... 
     return true; 
    } else { 
     return false; 
    } 
    } 
}); 

remitir este LINKLINK

+0

Quiere desactivar el botón Acción, no evitar que el teclado se oculte. – Ronnie

3
setOnEditorActionListener(new TextView.OnEditorActionListener() { 
if (txtView.getText().toString().trim().length() == 0) { 
    Toast.makeText(getApplicationContext(), "Please Enter some text to search", 
    Toast.Short).show(); 
    return true; // returning true will keep the keyboard on 
} 
else search(); 
Cuestiones relacionadas