El usuario presiona el botón ocultar teclado o el botón Atrás. Entonces, necesito despejar el foco en SearchView cuando el usuario está ocultando el teclado.
Intenté esto pero no funciona. el foco permanece cuando el usuario oculta el teclado.
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { searchView.clearFocus(); return false; } @Override public boolean onQueryTextChange(String newText) { app.requests.getApi().search(newText).enqueue(SearchFragment.this); return false; } });y esto:
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { app.functions.logWrite("has focus to searchview"); } else { //code } } });De acuerdo, intente esto, lamentablemente necesita el uso de una biblioteca, pero lo hace más fácil.
En su build.gradle : agregue esto:
dependencies { implementation 'net.yslibrary.keyboardvisibilityevent:keyboardvisibilityevent:3.0.0-RC2' } Regístrese para los eventos del teclado usando la biblioteca KeyboardVisibilityEvent como esta en el fragmento/clase donde se declara SearchView :
KeyboardVisibilityEvent.setEventListener( getActivity(), new KeyboardVisibilityEventListener() { @Override public void onVisibilityChanged(boolean isOpen) { if (!isOpen) { View focusedView = getWindow().getCurrentFocus(); if (focusedView != null && focusedView instanceof SearchView) { // does SearchView have focus? searchView.clearFocus(); } } } }); searchView.clearFocus(); funciona suponiendo que tiene otra vista enfocable en la jerarquía, si no, agregue esto a su diseño de fragmentos:
android:focusableInTouchMode="true" Alternativamente, simplemente llame a focus(); en cualquier otro elemento de vista en el que desee recibir atención.
Esto es lo que uso para manejar los clics en el botón Atrás para SearchView , onBackPressed()
@Override public void onBackPressed() { if (!searchView.isIconified()) { searchView.setIconified(true); ANY_VIEW_IN_YOUR_LAYOUT.requestFocus(); } else super.onBackPressed(); }Espero que esto ayude. No dude en pedir aclaraciones...