2

I'm trying to have a Fragment inside a FragmentPagerAdapter have its own onclicklistener for a MenuItem.

In other words, I'm trying to use an Activity's onOptionsItemSelected method inside a Fragment

How do I do this?

I've tried using onContextItemSelected(MenuItem theItem) and onOptionsItemSelected(MenuItem theItem) to no avail

Ryan D'souza
  • 653
  • 11
  • 22

1 Answers1

3
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    …
    setHasOptionsMenu(true);
    …
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    menu.clear();
    inflater.inflate(R.menu.your_menu, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.your_key_id:
        saveRoute();
        break;
    default:
        break;
    }
    return false;
}

Use this if you need one menu for all the pages.

Edit: If you need a specific menu on a specific page, see this: Android: Showing Action Bar menu items depending on ViewPager

Community
  • 1
  • 1
Francesco verheye
  • 1,574
  • 2
  • 14
  • 32