如何解雇键盘Android的搜索查看?键盘、Android

2023-09-12 02:05:16 作者:可遇不可求

我在动作条一个搜索查看。我想取消键盘,当用户使用输入完成。我对搜索查看以下queryTextListener

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; 
    } 
};

基于类似的问题

,以下code应该驳回键盘,但它并没有在这种情况下工作:

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);

我也试过:

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?

推荐答案

我试图做同样的事情。我需要启动 SearchActivity 从另一个活动并有搜索词出现在打开搜索字段,当它加载。我想以上,但最终所有的方法(类似于上述 Ridcully的回答)我设置一个变量搜索查看 onCreateOptionsMenu(),然后在 onQueryTextSubmit()名为 clearFocus()搜索查看当用户提交了一个新的搜索

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;
}