AndroidアプリでActionBarにSearchViewを実装する際のソフトキーボードを非表示にする方法は、以下の通りです。
今回は、Fragmentに
レイアウトファイル
menu/search.xml
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/search"
android:title="@string/search"
android:icon="@drawable/ic_baseline_search_white_24"
android:orderInCategory="100"
app:showAsAction="collapseActionView|ifRoom"
app:actionViewClass="android.widget.SearchView"/>
</menu>
Fragment
HogeFragment.java
public class HogeFragment extends Fragment
private SearchView searchView;
...
@Override
public void onCreate(Bundle saveInterface) {
super.onCreate(saveInterface);
// FragmentでMenuを表示する為に必要
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
searchView = (SearchView) menu.findItem(R.id.search).getActionView();
// 虫眼鏡アイコンの表示設定
this.searchView.setIconifiedByDefault(false);
// リスナーの設定
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if(!hasFocus){
hideIMM(view.findFocus());
}
}
});
private void hideIMM(View view) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(searchView.getWindowToken(),0);
}
};
困ったところ
setOnFocusChangeListener()だと思っていたら、setOnQueryTextFocusChangeListener()だったでござる。
参考
StackOverFlow -Android SearchView OnFocusChangeListener: onFocusChange is not called at all-
SearchView Androidデベロッパー Android開発者]