5
public class BFragmentTab extends Fragment {

    @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            return inflater.inflate(R.layout.recents, container, false);
     }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        menu.clear();
        MenuItem filter = menu.findItem(R.id.filter);
        MenuItem refresh = menu.findItem(R.id.refresh);
        //depending on you conditions, either enable/disable
        filter.setEnabled(false);
        refresh.setEnabled(false);
        super.onPrepareOptionsMenu(menu);
    }
}

I am trying to call my onPrepareOptionsMenu inside my Fragment class, buts its not getting called. I want to refresh my menu item when i click on an action tab inside my action bar.

mr.VVoo
  • 2,265
  • 20
  • 30
theJava
  • 14,620
  • 45
  • 131
  • 172

2 Answers2

14

Call setHasOptionsMenu(true) in onAttach method

Dmitry Zaytsev
  • 23,650
  • 14
  • 92
  • 146
  • Is there an advantage to calling in onAttach rather than onCreateView ? – Jonathan Caryl Mar 19 '13 at 14:22
  • @DmitryZaitsev: I get a null pointer exception in my onPrepareOptionsMenu method. – theJava Mar 19 '13 at 14:30
  • 1
    @theJava at leas it's called, right? :) You probably should call `super.onPrepareOptionsMenu` before everything else – Dmitry Zaytsev Mar 19 '13 at 14:31
  • For who arrives here using API 22.1.1 I just found out that the libray is bugged and onPrepareOptionsMenu is skipped from calling... Please read http://stackoverflow.com/a/30199286/3397345 – Davideas May 18 '15 at 15:12
0

I got the same error and in my case there was an error in my xml layout file for one of the sub-activity.

Surprisingly Eclipse didn't show the error but after removing it, the program worked.

Bilbo Baggins
  • 3,644
  • 8
  • 40
  • 64