Skip to content
Advertisement

Show/hide Searchview using onOptionsItemSelected

I want to make my Searchview to be visible only when I open product option from the drawer, to do that I am trying using onOptionsItemSelected method to listen which options is being used. The problem is I am always get a NullPointerException everytime I tried to get my SearchView id from onOptionsItemSelected.

I knew how to hide the SearchView in onCreateOptionsMenu using :

menu.findItem(R.id.action_search).setVisible(false);

This is the source code for my onCreateOptionsMenu :

JavaScript

But I can’t do the same thing in onOptionsItemSelected method, because the argument it used was MenuItem instead of Menu.

This is my latest try for the onOptionsItemSelected method :

JavaScript

And this is my res/menu/main.xml file :

JavaScript

Advertisement

Answer

I laready found answer! Apparently I don’t need onOptionsItemSelected at all.

I am using NavController on my DrawerLayout, so the easier way to make a listener is using onDestinationChanged method inside onCreateOptionsMenu

This is the result :

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement