Android:在配置更改中,searchView中的文本消失

时间:2015-09-26 05:23:14

标签: android configuration

我在searchView中输入的文字在配置更改时消失 我已经在处理配置更改,但仍然无法正常工作 因为我使用了片段,所以下面的代码写在片段内 请解决我的问题。
我的问题是我无法在onActivityCreated方法中检索savedInstance 以下是我的代码:
有用代码的片段

private String searchQuery="";

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            if(savedInstanceState != null)
            searchQuery = savedInstanceState.getString(Tag.SEARCH_QUERY);
        }

          @Override
        public void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            outState.putString(Tag.SEARCH_QUERY, searchQuery);

        }

 @Override
        public void onCreateOptionsMenu(Menu menu,MenuInflater menuInflater) {
            // Inflate the menu; this adds items to the action bar if it is present.
            menuInflater.inflate(R.menu.menu_search, menu);
            MenuItem menuItem = menu.findItem(R.id.action_search);
            SearchView searchView = null;
            if (menuItem != null)
                searchView = (SearchView) menuItem.getActionView();

            if (searchView != null) {
                searchView.setQuery(searchQuery,false);
                searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

                    @Override
                    public boolean onQueryTextSubmit(String query) {
                        //searching is done in async task
                        searchQuery = query;
                        NetworkUtility.onProgressBarShow(getActivity());
                        MyAsyncTaskDownloadDetails myAsyncTaskDownloadDetails = new MyAsyncTaskDownloadDetails();
                        myAsyncTaskDownloadDetails.execute(new String[]{Tag.PLP_URL + query, Tag.PLP,""});
                        return true;
                    }


                    @Override
                    public boolean onQueryTextChange(String newText) {
                        return true;
                    }
                });
            }
            super.onCreateOptionsMenu(menu, menuInflater);
        }
    }

1 个答案:

答案 0 :(得分:0)

首先您要在onQueryTextSubmit回调中保存 queryText ,这意味着searchQuery将保持为空,除非用户提交了搜索查询,请记住这一点。

其次尝试以下代码。它将起作用我已经测试过了。

if(searchQuery.length()>0){

    //See this commented code
    //  if(Utils.hasIceCreamSandwich()) {
    //      searchMenuItem.expandActionView();
    //  }else {
    //      MenuItemCompat.expandActionView(searchMenuItem);
    //  }

    MenuItemCompat.expandActionView(menuItem);
    searchView.setQuery(searchQuery, false);
}