简体   繁体   English

工具栏中的SearchView默认情况下不会扩展

[英]SearchView in toolbar not expanding by default

I created a searchview and I like to get focus on search view when the searchactivity is launched, after referring some stackoverflow's questions, I got a point to setIconifiedBydefault(false); 我创建了一个searchview,我希望在启动searchactivity时专注于搜索视图,在提到了一些stackoverflow的问题之后,我得到了setIconifiedBydefault(false);的提示。 however it doesn't work, it works when I touch the search icon. 但是它不起作用,当我触摸搜索图标时它会起作用。 guide me if I'm wrong, Here is my code. 如果我错了,请指导我,这是我的代码。

public boolean onCreateOptionsMenu(Menu menu) {


        final SearchView searchView = new SearchView(this);

        searchView.setIconifiedByDefault(false);
        searchView.setQueryHint(this.getResources().getString(R.string.search_hint));
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String query) {
                try {
                    query = URLEncoder.encode(query, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                searchView.clearFocus();

                Intent intent = new Intent(getApplicationContext(), SearchActivity.class);
                intent.putExtra("query", query);
                intent.putExtra("search", "true");
                startActivity(intent);
                return true;
            }

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

        });

        //TODO make menu an xml item
        menu.add("search")
                .setIcon(R.drawable.ic_action_search)
                .setActionView(searchView)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM|MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);

        return true;
    }

I think you need to call expandActionView(). 我认为您需要调用expandActionView()。

             ...
             menu.add("search")
                    .setIcon(R.drawable.ic_action_search)
                    .setActionView(searchView)
                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM|MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
             searchView.expandActionView();
             ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM