如何在 Android SearchView 中关闭键盘?

发布于 2024-12-04 13:43:49 字数 1049 浏览 3 评论 0原文

我在 ActionBar 中有一个 searchView 。我想在用户完成输入后关闭键盘。我在 searchView 上有以下 queryTextListener

final SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() { 
    @Override 
    public boolean onQueryTextChange(String newText) { 
        // Do something 
        return true; 
    } 

    @Override 
    public boolean onQueryTextSubmit(String query) {

        showProgress();
        // Do stuff, make async call

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        return true; 
    } 
};

基于类似的问题,以下代码应该关闭键盘,但在这种情况下不起作用:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

我也尝试过:

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchView.getWindowToken(), 0);

两者都不起作用。我不确定这是否是 Honeycomb 特定的问题,或者是否与 ActionBar 中的 searchView 有关,或两者兼而有之。有谁让它工作或知道为什么它不起作用?

I have a searchView in the ActionBar. I want to dismiss the keyboard when the user is done with input. I have the following queryTextListener on the searchView

final SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() { 
    @Override 
    public boolean onQueryTextChange(String newText) { 
        // Do something 
        return true; 
    } 

    @Override 
    public boolean onQueryTextSubmit(String query) {

        showProgress();
        // Do stuff, make async call

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        return true; 
    } 
};

Based on similar questions, the following code should dismiss the keyboard, but it doesn't work in this case:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

I've also tried:

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchView.getWindowToken(), 0);

Neither one works. I'm not sure if this is a Honeycomb specific problem or if it's related to the searchView in the ActionBar, or both. Has anyone gotten this working or know why it does not work?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

故人的歌 2024-12-11 13:43:49

我正在尝试做类似的事情。我需要从另一个 Activity 启动 SearchActivity,并在加载时让搜索词出现在打开的搜索字段中。我尝试了上面的所有方法,但最后(类似于 Ridcully 的答案上面)我将一个变量设置为 SearchViewonCreateOptionsMenu() 中调用 onCreateOptionsMenu(),然后在 onQueryTextSubmit() 中调用 clearFocus()当用户提交新搜索时 SearchView

private SearchView searchView;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.search_menu, menu);
    searchView = (SearchView) menu.findItem(R.id.menu_search)
            .getActionView(); // set the reference to the searchView
    searchView.setOnQueryTextListener(this); 
    searchMenuItem = (MenuItem) menu.findItem(R.id.menu_search); 
    searchMenuItem.expandActionView(); // expand the search action item automatically
    searchView.setQuery("<put your search term here>", false); // fill in the search term by default
    searchView.clearFocus(); // close the keyboard on load
    return true;
}

@Override
public boolean onQueryTextSubmit(String query) {
    performNewSearch(query);
    searchView.clearFocus();
    return true;
}

I was trying to do something similar. I needed to launch the SearchActivity from another Activity and have the search term appear on the opened search field when it loaded. I tried all the approaches above but finally (similar to Ridcully's answer above) I set a variable to SearchView in onCreateOptionsMenu() and then in onQueryTextSubmit() called clearFocus() on the SearchView when the user submitted a new search:

private SearchView searchView;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.search_menu, menu);
    searchView = (SearchView) menu.findItem(R.id.menu_search)
            .getActionView(); // set the reference to the searchView
    searchView.setOnQueryTextListener(this); 
    searchMenuItem = (MenuItem) menu.findItem(R.id.menu_search); 
    searchMenuItem.expandActionView(); // expand the search action item automatically
    searchView.setQuery("<put your search term here>", false); // fill in the search term by default
    searchView.clearFocus(); // close the keyboard on load
    return true;
}

@Override
public boolean onQueryTextSubmit(String query) {
    performNewSearch(query);
    searchView.clearFocus();
    return true;
}
冬天的雪花 2024-12-11 13:43:49

简单、开门见山、干净:

  @Override
  public boolean onQueryTextSubmit(String query) {
      // your search methods
      searchView.clearFocus();
      return true;
  }

Simple, straight to the point and clean:

  @Override
  public boolean onQueryTextSubmit(String query) {
      // your search methods
      searchView.clearFocus();
      return true;
  }
心碎的声音 2024-12-11 13:43:49

只需在 onQueryTextSubmit 上返回 false 即可,如下所示

@Override
public boolean onQueryTextSubmit(String s) {
     return false;
}

just return false on onQueryTextSubmit just like below

@Override
public boolean onQueryTextSubmit(String s) {
     return false;
}
若无相欠,怎会相见 2024-12-11 13:43:49

对我来说,以上所有内容都不适用于第一次提交。它被隐藏起来,然后立即重新显示键盘。我必须将 clearFocus() 发布到视图的处理程序上,以使其在完成其他所有操作后发生。

mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                if (!"".equals(query)) {
                    mSearchView.post(new Runnable() {
                        @Override
                        public void run() {
                            mSearchView.clearFocus();
                        }
                    });
                }
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });

For me, none of the above was working on the first submit. It was hiding and then immediately re-showing the keyboard. I had to post the clearFocus() on the view's handler to make it happen after it was done with everything else.

mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                if (!"".equals(query)) {
                    mSearchView.post(new Runnable() {
                        @Override
                        public void run() {
                            mSearchView.clearFocus();
                        }
                    });
                }
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
墟烟 2024-12-11 13:43:49

如果你打电话

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchView.getWindowToken(), 0);

然后然后就可以了

otherWidget.requestFocus();

Somehow it works if you call

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchView.getWindowToken(), 0);

and then

otherWidget.requestFocus();
仙女山的月亮 2024-12-11 13:43:49

对我来说,以下工作有效:

在我的活动中,我有一个成员变量

private SearchView mSearchView;

onCreateOptionsMenu() 中,我像这样设置该变量:

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.library, menu);
    mSearchView = (SearchView)menu.findItem(R.id.miSearch).getActionView();
    mSearchView.setOnQueryTextListener(this);
    return true;
}   

最后在 QueryTextListener 中,我这样做:

mSearchView.setQuery("", false);
mSearchView.setIconified(true); 

我查看了SearchView的源代码,如果您不将查询文本重置为空字符串,SearchView就会这样做,并且也不会删除键盘。实际上,在源代码中深入研究,结果是一样的,yuku 建议,但我仍然更喜欢我的解决方案,因为我不必搞乱那些低级的东西。

For me, the following works:

In my activity I have a member variable

private SearchView mSearchView;

In onCreateOptionsMenu() I set that variable like so:

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.library, menu);
    mSearchView = (SearchView)menu.findItem(R.id.miSearch).getActionView();
    mSearchView.setOnQueryTextListener(this);
    return true;
}   

In the QueryTextListener at last, I do this:

mSearchView.setQuery("", false);
mSearchView.setIconified(true); 

I had a look at the source code of SearchView, and if you do not reset the query text to an empty string, the SearchView just does that, and does not remove the keyboard neither. Actually, drilling down deep enough in the source code, it comes to the same, yuku suggested, but still I like my solution better, as I do not have to mess around with those low level stuff.

凉宸 2024-12-11 13:43:49

编辑:我在顶部添加了更好的解决方案,但也保留了旧答案作为参考。

 @Override
        public boolean onQueryTextSubmit(String query) {

                  searchView.clearFocus();
            return false;
        }

原始答案:我使用 setOnQueryTextListener 进行编程。当搜索视图隐藏时,键盘消失,然后当它再次可见时,键盘不会弹出。

    //set query change listener
     searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){
        @Override
        public boolean onQueryTextChange(String newText) {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public boolean onQueryTextSubmit(String query) {
            /**
             * hides and then unhides search tab to make sure keyboard disappears when query is submitted
             */
                  searchView.setVisibility(View.INVISIBLE);
                  searchView.setVisibility(View.VISIBLE);
            return false;
        }

     });

Edit: I added the better solution on top, but also kept the old answer as a reference.

 @Override
        public boolean onQueryTextSubmit(String query) {

                  searchView.clearFocus();
            return false;
        }

Original Answer: I programmed using a setOnQueryTextListener. When the searchview is hidden the keyboard goes away and then when it is visible again the keyboard does not pop back up.

    //set query change listener
     searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){
        @Override
        public boolean onQueryTextChange(String newText) {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public boolean onQueryTextSubmit(String query) {
            /**
             * hides and then unhides search tab to make sure keyboard disappears when query is submitted
             */
                  searchView.setVisibility(View.INVISIBLE);
                  searchView.setVisibility(View.VISIBLE);
            return false;
        }

     });
土豪 2024-12-11 13:43:49

如果有人正在寻找如何折叠 searchView/键盘,请使用下面的代码

     /*
        setup close button listener
     */
    searchView.findViewById<ImageView>(R.id.search_close_btn).setOnClickListener {
        adapter.filter(null)//reset default list
        searchView.onActionViewCollapsed() //collapse SearchView/Keyboard
        true
    }

    /*
        setup text change listener
     */
    searchView.setOnQueryTextListener(object:SearchView.OnQueryTextListener{
        override fun onQueryTextSubmit(query: String?): Boolean {

            adapter.filter(if(query.isNullOrEmpty()) "" else query)

            searchView.onActionViewCollapsed() //collapse SearchView/Keyboard
            return true
        }

        override fun onQueryTextChange(newText: String?): Boolean {
            adapter.filter(if(newText.isNullOrEmpty()) "" else newText)
            return true
        }
    })

if someone is looking how to collpase searchView/keyboard, use below code

     /*
        setup close button listener
     */
    searchView.findViewById<ImageView>(R.id.search_close_btn).setOnClickListener {
        adapter.filter(null)//reset default list
        searchView.onActionViewCollapsed() //collapse SearchView/Keyboard
        true
    }

    /*
        setup text change listener
     */
    searchView.setOnQueryTextListener(object:SearchView.OnQueryTextListener{
        override fun onQueryTextSubmit(query: String?): Boolean {

            adapter.filter(if(query.isNullOrEmpty()) "" else query)

            searchView.onActionViewCollapsed() //collapse SearchView/Keyboard
            return true
        }

        override fun onQueryTextChange(newText: String?): Boolean {
            adapter.filter(if(newText.isNullOrEmpty()) "" else newText)
            return true
        }
    })
瞄了个咪的 2024-12-11 13:43:49

在我正在处理双窗格活动的平板电脑应用程序中,我只编写了

f.getView().requestFocus(); // f 是搜索的目标片段

,这足以在搜索后关闭软键盘。无需使用InputMethodManager

In a tablet app I'm working on with a dual pane activity, I've wrote only

f.getView().requestFocus(); // f is the target fragment for the search

and that was enough to dismiss the soft keyboard after a search. No need to use InputMethodManager

帅气尐潴 2024-12-11 13:43:49

我使用 ActionBarSherlock 4.3 并且有一个 ProgressDialog。当我在 postExecute 方法中关闭它时,Searchview 获得焦点。解决这个问题:

//Handle intent and hide soft keyboard
    @Override
    protected void onNewIntent(Intent intent) {
        setIntent(intent);
        handleIntent(intent);
        searchView.setQuery("", false);
        searchView.setIconified(true);
        searchView.clearFocus();
    }

    /*When dismiss ProgressDialog, searchview gain focus again and shows the keyboard. I  call clearFocus() to avoid it.*/

    AsyncTask.onPostExecute(){
      if(pd!=null)
        pd.dismiss();
      if(searchView!=null)
        searchView.clearFocus();
    }

希望有帮助。

I used ActionBarSherlock 4.3 and I have a ProgressDialog. When I dismiss it in postExecute method, Searchview gain focus. To fix that:

//Handle intent and hide soft keyboard
    @Override
    protected void onNewIntent(Intent intent) {
        setIntent(intent);
        handleIntent(intent);
        searchView.setQuery("", false);
        searchView.setIconified(true);
        searchView.clearFocus();
    }

    /*When dismiss ProgressDialog, searchview gain focus again and shows the keyboard. I  call clearFocus() to avoid it.*/

    AsyncTask.onPostExecute(){
      if(pd!=null)
        pd.dismiss();
      if(searchView!=null)
        searchView.clearFocus();
    }

Hope it helps.

手心的海 2024-12-11 13:43:49

你可以使用它。

if (isKeybordShowing(MainActivity.this, MainActivity.this.getCurrentFocus())) {
    onBackPressed();
}

public boolean isKeybordShowing(Context context, View view) {
    try {
        InputMethodManager keyboard = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        keyboard.hideSoftInputFromWindow(view.getWindowToken(), 0);
        return keyboard.isActive();
    } catch (Exception ex) {
        Log.e("keyboardHide", "cannot hide keyboard", ex);
        return false;
    }
}

You can use it.

if (isKeybordShowing(MainActivity.this, MainActivity.this.getCurrentFocus())) {
    onBackPressed();
}

public boolean isKeybordShowing(Context context, View view) {
    try {
        InputMethodManager keyboard = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        keyboard.hideSoftInputFromWindow(view.getWindowToken(), 0);
        return keyboard.isActive();
    } catch (Exception ex) {
        Log.e("keyboardHide", "cannot hide keyboard", ex);
        return false;
    }
}
兔姬 2024-12-11 13:43:49

如果您是 kotlin 开发人员,则隐藏或显示软键盘的最简单方法是创建一个简单的 Kotlin 扩展函数 并添加以下代码

对于 kotlin 开发人员

fun View.hideSoftKeyboard() {
val context = context ?: return // get the context
val imm = ContextCompat.getSystemService(context, InputMethodManager::class.java)
imm?.hideSoftInputFromWindow(this.windowToken, 0) // you can get the current windowtoken from view where you call this function

}

对于 Java 开发人员(java没有扩展功能)因为它纯粹是oop的语言

public class Utils {

public static void hideSoftKeyboard(View view) {
    Context context = view.getContext();
    if (context == null) {
        return;
    }

    InputMethodManager imm = ContextCompat.getSystemService(context, InputMethodManager.class);
    if (imm != null) {
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}

}

The easiest and the simple way to hide or show the soft keyboard if you are kotlin developer create a simple Kotlin extension function and add this following code

For kotlin developer's

fun View.hideSoftKeyboard() {
val context = context ?: return // get the context
val imm = ContextCompat.getSystemService(context, InputMethodManager::class.java)
imm?.hideSoftInputFromWindow(this.windowToken, 0) // you can get the current windowtoken from view where you call this function

}

For Java Developer (java has a no extension function) because it is purely oop's language

public class Utils {

public static void hideSoftKeyboard(View view) {
    Context context = view.getContext();
    if (context == null) {
        return;
    }

    InputMethodManager imm = ContextCompat.getSystemService(context, InputMethodManager.class);
    if (imm != null) {
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}

}

Saygoodbye 2024-12-11 13:43:49

两个对我有用的解决方案,第一个使用 SearchView 实例:

private void hideKeyboard(){
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
}

第二个解决方案:

private void hideKeyboard(){
            InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
            inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
 }

Two solutions that worked for me, the first one using the SearchView instance:

private void hideKeyboard(){
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
}

Second solution:

private void hideKeyboard(){
            InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
            inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
 }
倚栏听风 2024-12-11 13:43:49

下面的代码可以帮助我在 Searchview 中隐藏键盘

MenuItem searchItem = baseMenu.findItem(R.id.menuSearch);

edtSearch= (EditText) searchItem.getActionView().findViewById(R.id.search_src_text);

MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
                        @Override
                        public boolean onMenuItemActionExpand(MenuItem item) {
                            edtSearch.post(new Runnable() {
                                @Override
                                public void run() {
                                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                                    imm.hideSoftInputFromWindow(searchEditText.getWindowToken(), 0);
                                }
                            });
                            return true;
                        }

                        @Override
                        public boolean onMenuItemActionCollapse(MenuItem item) {
                            return true;
                        }
                    });

Below Code is working for me to hide keyboard in Searchview

MenuItem searchItem = baseMenu.findItem(R.id.menuSearch);

edtSearch= (EditText) searchItem.getActionView().findViewById(R.id.search_src_text);

MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
                        @Override
                        public boolean onMenuItemActionExpand(MenuItem item) {
                            edtSearch.post(new Runnable() {
                                @Override
                                public void run() {
                                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                                    imm.hideSoftInputFromWindow(searchEditText.getWindowToken(), 0);
                                }
                            });
                            return true;
                        }

                        @Override
                        public boolean onMenuItemActionCollapse(MenuItem item) {
                            return true;
                        }
                    });
伴我心暖 2024-12-11 13:43:49

你为什么不试试这个呢?当您触摸 X 按钮时,无论如何都会触发搜索视图的焦点。

ImageView closeButton = (ImageView)searchView.findViewById(R.id.search_close_btn);
        closeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText et = (EditText) findViewById(R.id.search_src_text);
                et.setText("");`enter code here`
                searchView.setQuery("", false);
                searchView.onActionViewCollapsed();
                menuSearch.collapseActionView();
            }
        });

Why dont you try this? When you touch the X button, you trigger a focus on the searchview no matter what.

ImageView closeButton = (ImageView)searchView.findViewById(R.id.search_close_btn);
        closeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText et = (EditText) findViewById(R.id.search_src_text);
                et.setText("");`enter code here`
                searchView.setQuery("", false);
                searchView.onActionViewCollapsed();
                menuSearch.collapseActionView();
            }
        });
痴情 2024-12-11 13:43:49
fun View.hideKeyboard() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(windowToken, 0)
}
fun View.hideKeyboard() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(windowToken, 0)
}
め可乐爱微笑 2024-12-11 13:43:49
 @Override
    public void onResume() {
        super.onResume();
        searchView.clearFocus();
    }

我尝试了上面所有的答案,但没有一个起作用,清除对 Resume 的关注对我有用

 @Override
    public void onResume() {
        super.onResume();
        searchView.clearFocus();
    }

I tried all the answers above but none worked, clearing focus onResume worked for me

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文