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 !
- Botón setonclicklistener error
- Cómo obtener OnClick () de los botones agregados mediante programación?
- Adaptador personalizado para gridview en android
- Cómo ocultar / mostrar el botón en el widget de pantalla de inicio de Android
- RecyclerView onItemClicked devolución de llamada
- Array @OnClick con identificadores opcionales (ButterKnife)
- Android: El botón OnClickListener no funciona
- Android.os.FileUriExposedException: file.jpg expuesto más allá de la aplicación a través de ClipData.Item.getUri ()
- Listview no se puede hacer clic cuando se puede seleccionar la vista de texto dentro de esa vista de lista
- Manejo de eventos táctiles - onInterceptTouchEvent y onTouchEvent
- ¿Cómo abrir el menú deslizante en el evento de clic del botón?
- Hacer diferencias entre setOnClickListener y setOnTouchListener
- Vistas superpuestas de Android y OnClick
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); } } }
- Utilizar GSON para analizar un JSON con "clave" dinámica y "valor" en android
- Java.lang.UnsupportedOperationException: No se puede convertir a dimension: type = 0x12