'ViewPager menu icon delay when swiping
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.
Solution 1:[1]
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.
Solution 2:[2]
Never had this issue with ViewPager. But the new ViewPager2 acts this way. And it is frustrating because there is no way to change the scroll speed since the default is toooo slow.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Vasily Kabunov |
Solution 2 | chitgoks |