Android: Showing Action Bar Menu Items Depending On ViewPager
Solution 1:
invalidateOptionsMenu
make the system calls the method onPrepareOptionsMenu
, so you can override this method as follows:
public boolean onPrepareOptionsMenu(Menu menu) {
int pageNum = getCurrentPage();
if (pageNum == 1) {
menu.findItem(R.id.menu_search).setVisible(true);
}
else {
menu.findItem(R.id.menu_search).setVisible(false);
}
}
public void onPageSelected(int pageNum) {
invalidateOptionsMenu();
}
Solution 2:
You can implement onCreateOptionsMenu() in your Fragment and set 'setHasOptionsMenu(true)' for the fragment
Solution 3:
a possible solution for this problem would be inflating your custom menu inside the activity hosts your ViewPager and getting a menu reference as below:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.custom_menu, menu);
customMenu = menu;
return super.onCreateOptionsMenu(menu);
}
after that you can easily hide/show the menu's items without any delay inside onPageSelected method as below:
@Override
public void onPageSelected(int position) {
switch (position) {
case 0: {
customMenu.getItem(0).setVisible(false);
break;
}
case 1: {
customMenu.getItem(0).setVisible(true);
break;
}
}
Solution 4:
I used Nermeen's answer and managed to get it without any delay.
I don't inflate anything in onCreateOptionsMenu
, but use it to get a reference to the menu:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
customMenu = menu;
return super.onCreateOptionsMenu(menu);
}
Then, in onPrepareOptionsMenu()
, I call the viewpager getCurrentItem()
(should be something like viewPager.getCurrentItem()
), call invalidateOptionsMenu()
and inflate whatever menu I want in that page using the customMenu reference I created in onCreateOptionsMenu()
.
Post a Comment for "Android: Showing Action Bar Menu Items Depending On ViewPager"