android searchview setOnActionExpandListener on Honeycomb 3.2

前端 未结 5 1970
無奈伤痛
無奈伤痛 2020-12-15 23:32

I\'m developing an app for Android 3.2 and greater with android-support-v4. I need to implement OnActionExpandListener for \"intercept\" when Searc

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-15 23:59

    I found that MenuItemCompat.setOnActionExpandListener(...) is not working if you don't pass:

        searchItem
                .setShowAsAction(MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW
                        | MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
    

    But this is changing the SearchView and is replacing the DrawerToggle with back arrow.

    I wanted to keep the original views and still track the Expanded/Collapsed state and use supported Search View.

    Solution:

    When android.support.v7.widget.SearchView is changing the view state the LinearLayout view's, with id android.support.v7.appcompat.R.id.search_edit_frame, visibility value is being changed from View.VISIBLE to View.GONE and opposite. So I add ViewTreeObserver to track the visibility change of the search edit frame.

    menu_search.xml:

    
    
    
    
    
    

    In the activity:

    import android.support.v4.view.MenuItemCompat;
    import android.support.v7.widget.SearchView;
    import android.view.Menu;
    import android.view.MenuItem;
    
    ..........
    
    private View mSearchEditFrame;
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_search, menu);
        MenuItem searchItem = (MenuItem) menu.findItem(R.id.action_search);
    
        SearchView searchView = (SearchView) MenuItemCompat
                .getActionView(searchItem);
        searchView.setSubmitButtonEnabled(false);
        mSearchEditFrame = searchView
                .findViewById(android.support.v7.appcompat.R.id.search_edit_frame);
    
        ViewTreeObserver vto = mSearchEditFrame.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            int oldVisibility = -1;
    
            @Override
            public void onGlobalLayout() {
    
                int currentVisibility = mSearchEditFrame.getVisibility();
    
                if (currentVisibility != oldVisibility) {
                    if (currentVisibility == View.VISIBLE) {
                        Log.v(TAG, "EXPANDED");
                    } else {
                        Log.v(TAG, "COLLAPSED");
                    }
    
                    oldVisibility = currentVisibility;
                }
    
            }
        });
    
        return super.onCreateOptionsMenu(menu);
    }
    

    Thanks!

提交回复
热议问题