Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android: Update the ActionBar items depending on each Fragment in a ViewPager?

I have a flag/bookmark button in the Action Bar that I want to be toggled on or off depending which Fragment is in view of the ViewPager.

If the user flags a fragment in the ViewPager, it will be set to enabled. When the user swipes to the next one, I want the action bar button to update to unflagged. Now, I'm able to change the state of the button by having two menu items and hide one, show one when clicked.

Here's the code in my Activity to toggle the Action Bar button:

public boolean onOptionsItemSelected(MenuItem item) {
    int currentItem = mPager.getCurrentItem();
    switch (item.getItemId()) {
    case R.id.menu_flag:
        mFlagged = true;
        supportInvalidateOptionsMenu();
        return true;
    case R.id.menu_unflag:
        mFlagged = false;
        supportInvalidateOptionsMenu();
        return true;
    }
}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    MenuItem item_flag = menu.findItem(R.id.menu_flag);
    MenuItem item_unflag = menu.findItem(R.id.menu_unflag);
    if (mFlagged) {
        //If flagged
        //Show flagged item
        item_flag.setVisible(false).setEnabled(false);
        item_unflag.setVisible(true).setEnabled(true);
        item_flag.isVisible();
    } else {
        //If not flagged
        //Show unflagged icon
        item_flag.setVisible(true).setEnabled(true);
        item_unflag.setVisible(false).setEnabled(false);
    }

    return super.onPrepareOptionsMenu(menu);
}

The problem I'm having is that I can't access the menu item, save & restore the state of the button, i.e. if it's flagged or not from the fragment or the FragmentPagerAdapter.

How can I do this? Which level should I be accessing the Action Bar; Activity, PagerAdapter or the Fragments?

like image 489
Tim Kist Avatar asked Feb 27 '13 15:02

Tim Kist


1 Answers

Registering a ViewPager.OnPageChangeListener on your ViewPager should do the trick. Then, override onPageSelected(int pageNum) to receive callbacks when a page changes.

public void onPageSelected(int pageNum) {
     supportInvalidateOptionsMenu();
}
like image 169
onlythoughtworks Avatar answered Oct 20 '22 13:10

onlythoughtworks