Deshabilitar el botón de envío del teclado cuando no se ha escrito nada

Estoy creando una opción de búsqueda en una aplicación de Android.

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

He añadido esto a la EditText :

android:imeOptions="actionSearch"

Así que por eso el teclado tiene un botón "Buscar" en lugar del predeterminado "enter" / "done". (Sólo en caso de que se pregunte).

No podemos deshabilitar el botón de acción en el teclado de Android. Usted tendrá que conformarse con la comprobación de la cadena vacía en el oyente de la acción del redactor.

 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(); 

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

1) Quitar el androide: imeOptions = "actionSearch" del xml

2) Crear un TextWatcher personalizado addTextChangedListener (TextWatcher watcher) 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){} }); 

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

He aquí un ejemplo de código.

 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 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; } }); 

Implementar OnKeyListener en su Activity .

Agrega este keyListener a tu EditText .

  myEditText.setOnKeyListener(this); 

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 brindis cada vez que su EditText está vacío y presiona 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 KeyEvent, recibida como parámetro en el método onKey() .

Adjunte OnEditorActionListener a su campo de texto y devuelva true de su método onEditorAction, cuando actionId es igual a IME_ACTION_DONE . Esto evitará que el teclado suave se oculte:

 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; } } }); 

Refiérase a este LINK LINK

  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 intentar esto ..! Para el error de fantasía dilog

  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 } 

Utilice el código siguiente en Editar texto,

 android:imeOptions="flagNoEnterAction" 

No puedo establecer flagNoEnterAction = "false" Pero alguien puede ayudarte

  • ¿Cómo agregar documentación a atributos personalizados?
  • Atributo de envío de xml de fondo personalizado de Android
  • Alinear dos botones horizontalmente
  • Android scrollview ocultando el contenido superior en el diseño
  • Match_parent no funciona como se esperaba
  • Android El teclado suave flotará solo un diseño específico
  • Cómo dibujar un rectángulo con esquinas redondeadas con XML?
  • ¿Qué es android: includeFontPadding?
  • ¿Hay alguna manera de usar un tamaño de banner de anuncio variable?
  • Cómo crear mediante programación el diseño de un fragmento?
  • Android CalendarView desaceleración de diseño
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.