Ocultar el teclado cuando el usuario teclea en cualquier otro lugar de la pantalla en android

Tengo que ocultar el softkeypad en android cuando el usuario haga clic en cualquier lugar que no sea Edittext. Hay mucha ayuda para el iphone, pero no para Android. He intentado este código pero no funciona 🙁

final RelativeLayout base = (RelativeLayout) findViewById(R.id.RelativeLayout1); findViewById(R.id.base).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(base.getWindowToken(), 0); } }); 

Gracias por adelantado !

Puede usar el onTouchEvent() para ocultar el Softkeyboard .

 @Override public boolean onTouchEvent(MotionEvent event) { InputMethodManager imm = (InputMethodManager)getSystemService(Context. INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); return true; } 

Aunque esta solución funciona, pero lo mejor que yo sugiero es usar la respuesta a continuación, ya que da la mejor solución de cerrar el toque del teclado en cualquier otro lugar, a continuación, EditText.

Bueno, he hecho de esta manera:

Agregue código en su Actividad .

Esto funcionaría para Fragment también, no hay necesidad de agregar este código en Fragmento .

 @Override public boolean dispatchTouchEvent(MotionEvent ev) { View view = getCurrentFocus(); if (view != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) && view instanceof EditText && !view.getClass().getName().startsWith("android.webkit.")) { int scrcoords[] = new int[2]; view.getLocationOnScreen(scrcoords); float x = ev.getRawX() + view.getLeft() - scrcoords[0]; float y = ev.getRawY() + view.getTop() - scrcoords[1]; if (x < view.getLeft() || x > view.getRight() || y < view.getTop() || y > view.getBottom()) ((InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow((this.getWindow().getDecorView().getApplicationWindowToken()), 0); } return super.dispatchTouchEvent(ev); } 

Espero que esto te ayudará.

El mejor trabajo alrededor que encontré estaba usando como abajo,

Anule dispatchTouchEvent() y trate de obtener el área de EditText utilizando Rect

  @Override public boolean dispatchTouchEvent(MotionEvent ev) { int x = (int) ev.getX(); int y = (int) ev.getY(); if (ev.getAction() == MotionEvent.ACTION_DOWN && !getLocationOnScreen(etFeedback).contains(x, y)) { InputMethodManager input = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); input.hideSoftInputFromWindow(etFeedback.getWindowToken(), 0); } return super.dispatchTouchEvent(ev); } 

Método que cacula 4 esquina de Vista (aquí su EditText)

 protected Rect getLocationOnScreen(EditText mEditText) { Rect mRect = new Rect(); int[] location = new int[2]; mEditText.getLocationOnScreen(location); mRect.left = location[0]; mRect.top = location[1]; mRect.right = location[0] + mEditText.getWidth(); mRect.bottom = location[1] + mEditText.getHeight(); return mRect; } 

Usando el código anterior podemos detectar el área de EditText y podemos comprobar si el toque en la pantalla es parte del área de EditText o no. Si su parte de EditText entonces no hace nada deje que el tacto haga su trabajo, y si el tacto no contiene el área de EditText , simplemente cierre el softkeyboard.

******EDITAR******

Acabo de encontrar otro enfoque si no queremos dar ningún EditText como entrada y desea ocultar el teclado dentro de toda la aplicación cuando el usuario toca en cualquier otro lugar que no sea EditText. Entonces usted tiene que crear un BaseActivity y escribir el código global para ocultar el teclado como abajo,

  @Override public boolean dispatchTouchEvent(MotionEvent ev) { boolean handleReturn = super.dispatchTouchEvent(ev); View view = getCurrentFocus(); int x = (int) ev.getX(); int y = (int) ev.getY(); if(view instanceof EditText){ View innerView = getCurrentFocus(); if (ev.getAction() == MotionEvent.ACTION_UP && !getLocationOnScreen(innerView).contains(x, y)) { InputMethodManager input = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); input.hideSoftInputFromWindow(getWindow().getCurrentFocus() .getWindowToken(), 0); } } return handleReturn; } 

He intentado esto para ocultar el teclado. Debe pasar el método en su archivo de diseño.

 public void setupUI(View view) { // Set up touch listener for non-text box views to hide keyboard. if (!(view instanceof EditText)) { view.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { hideSoftKeyboard(LOGSignUpActivity.this); return false; } }); } //If a layout container, iterate over children and seed recursion. if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { View innerView = ((ViewGroup) view).getChildAt(i); setupUI(innerView); } } } 
  • Android - Bloques de CheckBox ExpandableListView.OnGroupClickListener
  • Cómo borrar el edittext cuando onclick en el botón
  • Phonegap 2.4.0 con Android 4.2 - comportamiento de doble clic extraño
  • Evento de clic transferido a la siguiente Actividad iniciada
  • ¿Cómo implementar el botón con doble prensa corta y continua?
  • Android: No se puede obtener un encabezado / pie de lista ListView que se puede hacer clic
  • Android one OnClick método para varios botones?
  • Cambio de fondo del elemento de vista de lista de Android
  • Realizar el botón Acción en Haga clic en Notificación personalizada: Android
  • Cómo eliminar el fondo de ImagePack en Android, pero sigo haciendo clic en Resaltar
  • ¿Cómo puedo inhabilitar todos los eventos táctiles en todos los niños de un ViewGroup?
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.