Android ActionBar: collapsible SearchView with action button

前端 未结 4 1920
孤城傲影
孤城傲影 2020-12-13 14:29

How to build ActionBar with collapsible search view with single action item visible, when search view is expanded? To be more descriptive, this is what I need:

4条回答
  •  执笔经年
    2020-12-13 15:22

    After considering the suggestions from comments, many googling and testing succeeded in obtaining the desired effect. I'm not proud of this solution but it works, it's not too complicated and should be enough for this case.

    In resume what I did:

    1. Placed SearchView with custom "add item" button in customView of ActionBar.
    2. Removed collapseActionView and android:actionLayout from search item in menu.xml
    3. Collapsing/expanding SearchView programmatically.

    Some code to better understand what I did. Maybe this can be useful for someone.

    menu.xml

    
    
    // ... other menu items
    

    actionbar_search.xml

    
    
        
    
        
    
    
    

    MainActivity.java

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // ...
        actionBar.setCustomView(R.layout.actionbar_search);
        actionBarCustomView = ab.getCustomView();
        searchView = ((SearchView) actionBarCustomView.findViewById(R.id.search_view));
        searchView.setOnCloseListener(new SearchView.OnCloseListener() {
            @Override
            public boolean onClose() {
                searchView.setVisibility(View.INVISIBLE);
                return false;
            }
        });
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            // ...
            case R.id.menu_search:
                if (searchView.getVisibility() == View.VISIBLE) {
                    searchView.setIconified(true);
                    searchView.setVisibility(View.INVISIBLE);
                } else {
                    searchView.setMaxWidth(abCustomView.getWidth() - addButton.getWidth());
                    searchView.setVisibility(View.VISIBLE);
                    searchView.setIconified(false);
                }
                break;
            // ...
        }
        return true;
    }
    
    @Override
    public void onBackPressed() {
    
        if (searchView.getVisibility() == View.VISIBLE) {
            searchView.setIconified(true);
            searchView.setVisibility(View.INVISIBLE);
            return;
        }
    
        // ...
    }
    

提交回复
热议问题