Expand Search View to use entire Action Bar (hide other things)

后端 未结 3 1905
挽巷
挽巷 2021-01-01 10:57

I have a SearchView inside my ActionBar, and I want to use the entire ActionBar when the search icon is pressed, but I can only use th

相关标签:
3条回答
  • 2021-01-01 11:22

    I tried this line of code to make the searchview expand the full width available. This works when there are other items shown in the actionbar either.

    searchView.setMaxWidth(android.R.attr.width);
    
    0 讨论(0)
  • 2021-01-01 11:34

    Well you could imitate that yourself by hiding all the other items when the SearchView is expanded:

    @Override
    public boolean onCreateOptionsMenu(final Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
    
        final MenuItem searchItem = menu.findItem(R.id.search);
        SearchView searchView = (android.widget.SearchView) searchItem.getActionView();
    
        // Detect SearchView icon clicks
        searchView.setOnSearchClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setItemsVisibility(menu, searchItem, false);
            }
        });
        // Detect SearchView close
        searchView.setOnCloseListener(new SearchView.OnCloseListener() {
            @Override
            public boolean onClose() {
                setItemsVisibility(menu, searchItem, true);
                return false;
            }
        });
    
        return super.onCreateOptionsMenu(menu);
    }
    
    private void setItemsVisibility(Menu menu, MenuItem exception, boolean visible) {
        for (int i=0; i<menu.size(); ++i) {
            MenuItem item = menu.getItem(i);
            if (item != exception) item.setVisible(visible);
        }
    }
    
    0 讨论(0)
  • 2021-01-01 11:41

    This would be a late answer but you could add this attribute to your menu item and the work is done for you.

    app:showAsAction="collapseActionView|always"
    

    Keyword here being the collapseActionView.

    0 讨论(0)
提交回复
热议问题