Tell me how can I hide one of the menu items in another activation? And now this item on all activites. In the onCreate method I wrote the following, but when I switch to activation, the program crashes.

MenuItem like = (MenuItem) findViewById(R.id.action_like); like.setVisible(false); 

Here is a glass

java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.MenuItem.setVisible (boolean)' on a null object reference at my.test.p1.ActivityAdd.onCreateOptionsMenu (ActivityAdd.java:121) at android.app.Activity. : 92) at android.support.v7.app.AppCompatDelegateImplBase $ AppCompatWindowCallbackBase.onCreatePanelMenu (AppCompatDelegateImprahl.d.d.d.d. app. os.Handler.dispatchMessage (Ha ndler.java:95) at android.os.Looper.loop (Looper.java:154) at android.app.ActivityThread.main (ActivityThread.java:6077) at java.lang.reflect.Method.invoke (Native Method) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run (ZygoteInit.java:865) at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:755)

    1 answer 1

    In the onCreate () method, you cannot access the menu, since it has not yet been created. Use onCreateOptionsMenu()

      @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.tool_sort, menu); MenuItem like = menu.findItem(R.id.action_like); like.setVisible(false); return true; } 
    • Posted by. Flies all the same. - Sergey
    • Attach a log of departure (Structure) in your question. - Flippy
    • Attached to your question - Sergey
    • Apparently, you give the wrong item id if the menu.findItem line (R.id.action_like) returns null to you - Kirill Stoianov
    • Alternatively, in the getMenuInflater (). Inflate line (R.menu.tool_sort, menu) you pass the wrong menu id and, accordingly, it does not have an element of the list you are looking for - Kirill Stoianov