Gabi Radu
Gabi Radu

Reputation: 1107

How can i access activity menu items from fragment in Android?

I have a class that extends ActionBarActivity and make use of a ViewPager as well. I want my menu to be availble in all the fragments (3 tabs)and not only see the menu (that happends) but to actually respond to the logic per each menu item.

In activity:

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

@Override
public boolean onOptionsItemSelected(MenuItem item) {
 ...
return super.onOptionsItemSelected(item);
}

In each fragment:

    setHasOptionsMenu(false);
    @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            inflater.inflate(R.menu.menu_main, menu);
            super.onCreateOptionsMenu(menu,inflater);
        }

    @Override
        public boolean onOptionsItemSelected(MenuItem item) {
             ...
            return false;
      }

In fragment nothing happends when I choose an option from the menu, and i don't understand why. I am doing something wrong, just don't spot it. Any ideas would be great. Thank you.

Upvotes: 2

Views: 2723

Answers (1)

Nick Pontiff
Nick Pontiff

Reputation: 144

In your fragment you must specify that there is a menu with setOptionsMenu(true)

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

Upvotes: 1

Related Questions