Dima
Dima

Reputation: 1510

Change button state (icon) of Action Bar

How i can dinamically change action button icon of Action Bar when i swipe fragments in ViewPager. Depending on fragment button must change state (icon).

Upvotes: 1

Views: 1547

Answers (2)

Dima
Dima

Reputation: 1510

I solved this problem:
1) I implement OnPageChangeLister
2) Invoke setIcon() in onPageScrollStateChanged()
3) MenuItem defined like global variable (field of class)

Upvotes: 1

Mike
Mike

Reputation: 2442

You can set the correct icon in onPrepareOptionsMenu, and then invalidate your action bar with invalidateOptionsMenu (or ActivityCompat.invalidateOptionsMenu if you are using the support library) when you want the icon to update.

For example:

@Override
public boolean onPrepareOptionsMenu (Menu menu) {
  MenuItem item = menu.findItem(R.id.my_menu_id);
  item.setIcon(getMenuItemIconResId());
}

@Override
public void onPageSelected(int position) {
  invalidateOptionsMenu();
}

Upvotes: 1

Related Questions