如何折叠searchView

时间:2014-07-30 03:21:42

标签: android android-fragments searchview

当我的片段被实例化时,搜索视图已经处于展开状态,我希望它最初折叠成搜索图标。这是我的xml

Search.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:yourapp="http://schemas.android.com/apk/res-auto"    >
<item
    android:id="@+id/search"
    android:title="@string/search_hint"
    android:showAsAction="always"
    yourapp:showAsAction="always"
    android:icon="@drawable/ic_action_search"

    yourapp:actionViewClass="android.support.v7.widget.SearchView" />

</menu>

我的片段类

@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        final InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
    }
    public ContentsFragment() {
        // TODO Auto-generated constructor stub
        this.setHasOptionsMenu(true);
    }

@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        Flag.f=1;
        super.onCreateOptionsMenu(menu, inflater);
        menu.clear();
        inflater.inflate(R.menu.search, menu);

         SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
          MenuItem searchItem = menu.findItem(R.id.search);
          SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
        searchView.setQueryHint("Search Articles");

        if (null != searchView) {
            searchView.setSearchableInfo(searchManager
                    .getSearchableInfo(getActivity().getComponentName()));
            searchView.setIconifiedByDefault(false);
        }

        SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
            public boolean onQueryTextChange(String newText) {
                // this is your adapter that will be filtered
                return true;
            }

            public boolean onQueryTextSubmit(String query) {
                Flag.querytext=query;
                final InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
                QueryFragment fragment2 = new QueryFragment();
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.frame_container, fragment2,query);
                fragmentTransaction.commit();
                return true;

            }
        };
        searchView.setOnQueryTextListener(queryTextListener);

    }

根据上面的代码,当片段刚刚实例化时,searchView已经被删除了。

当片段刚刚实例化时,如何折叠searchView,&amp;它应该在点击搜索图标时展开吗?

我希望我的问题很明确......

1 个答案:

答案 0 :(得分:3)

使用android:showAsAction="always|collapseActionView"