Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent SearchView from collapsing when pressing back

Tags:

android

I have a video player app where you can search for videos. My video player is just a View I hide and show whenever the user is actually playing a video.

I implemented Search as a SearchView menu item that feeds a fragment. When you click on a video, the video player view will show up and play such video. If you press then the back button, the video player should be closed.

Instead, Android is taking my back press as the trigger to collapse the searchview on the action bar first, then on a second press I am able to catch the onBackPressed method on my activity to close the video.

How can I hook up before the action is collapsed, so I can disable it and close my video player on the first click?

like image 986
MichelReap Avatar asked Mar 07 '23 16:03

MichelReap


1 Answers

I think the correct way to do this would be to add MenuItem.OnActionExpandListener to your SearchView item.

like so:

searchMenuItem.setOnActionExpandListener(new OnActionExpandListener() {

    @Override
    public boolean onMenuItemActionExpand(MenuItem item) {
        return true;
    }

    @Override
    public boolean onMenuItemActionCollapse(MenuItem item) {
        // return true if the item should collapse, false if collapsing should be suppressed.
        return false;
    }
});

You can view the official interface class reference here

like image 103
Sarthak Mittal Avatar answered Mar 10 '23 11:03

Sarthak Mittal