When swiping between tabs on my application, the menu icons have a distinct delay before they appear. If I click tabs, rather than swiping, they update immediately. I have different menu.xml files for each fragment, and inflate them inside each fragment's onCreateOptionsMenu.
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fodmap_menu, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
}
Notice the icon changes from the overflow to the magnifying glass instantly when the tabs are clicked, but distinctly delayed when swiping. I would like the icon to be updated as soon as the new tab is centered. On Pocket Cast's Discover menu the tabs with different menu icons seem to load them even before the swipe animation completes.
Instead of using a different menu inside each fragment of the view pager - inflate the menu, call invalidateOptionsMenu()
inside the ViewPager's onPageChangeListener
, and programmatically display desired menu icon's in onCreateOptionsMenu
, all inside the main activity instead of the fragments. The searchView listener is still handled in the fragment.
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
invalidateOptionsMenu();
}
@Override
public void onPageSelected(int position) {}
@Override
public void onPageScrollStateChanged(int state) {}
});
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.fodmap_menu, menu);
if (mViewPager.getCurrentItem()==0){
menu.findItem(R.id.action_search).setVisible(false);
} else if(mViewPager.getCurrentItem()==1){
menu.findItem(R.id.action_search).setVisible(true);
} else if(mViewPager.getCurrentItem()==2) {
menu.findItem(R.id.action_search).setVisible(false);
}
return super.onCreateOptionsMenu(menu);
}
There is no delay now and the menu icons update before the swipe animation finishes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With