[英]Searchview clear focus on hide keyboard
The user presses the hide keyboard button or the back button.用户按下隐藏键盘按钮或后退按钮。 So I need to clear focus on the SearchView when the user is hiding the keyboard.
因此,当用户隐藏键盘时,我需要清除对 SearchView 的关注。
I tried this but it's not working.我试过这个,但它不工作。 focus remains when the user hides the keyboard.
当用户隐藏键盘时焦点仍然存在。
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;
}
});
and this:和这个:
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
app.functions.logWrite("has focus to searchview");
} else {
//code
}
}
});
Okay so try this it needs the use of a library unfortunately but it makes it easier.好吧,试试这个,不幸的是它需要使用一个库,但它使它更容易。
In your build.gradle : add this:在您的build.gradle 中:添加:
dependencies {
implementation 'net.yslibrary.keyboardvisibilityevent:keyboardvisibilityevent:3.0.0-RC2'
}
Register for the keyboard events using KeyboardVisibilityEvent library like this in the fragment/class where SearchView
is declared:在声明
SearchView
的片段/类中使用KeyboardVisibilityEvent 库注册键盘事件,如下所示:
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();
works on the assumption you have another focusable view in the hierarchy, if not add this to your fragments layout:假设您在层次结构中有另一个可聚焦的视图,如果没有将其添加到您的片段布局中:
android:focusableInTouchMode="true"
Alternatively simply call focus();
或者简单地调用
focus();
on any other view element you want to receive focus.在您想要获得焦点的任何其他视图元素上。
This is what I use for handling back button clicks for SearchView
, by Overriding onBackPressed()
这就是我用来处理
SearchView
的后退按钮点击的方法,方法是覆盖onBackPressed()
@Override
public void onBackPressed() {
if (!searchView.isIconified()) {
searchView.setIconified(true);
ANY_VIEW_IN_YOUR_LAYOUT.requestFocus();
} else
super.onBackPressed();
}
Hope this helps.希望这可以帮助。 Feel free to ask for clarifications...
随时要求澄清...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.