I am using 4 fragments with view pager 2. And got this error suddenly. The crash does not always appear. I have searched other problems but I could not find any solution about viewpager2.
crash report from mobile could not get the full picture
setUpViewPager() calling this from onStart() of MainActivity
public void setupViewPager() {
MainActivityViewPager adapter = new MainActivityViewPager(getSupportFragmentManager(), getLifecycle());
binding.viewpager.setUserInputEnabled(false);
binding.viewpager.setOffscreenPageLimit(3);
binding.viewpager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageSelected(int position) {
if (prevMenuItem != null) {
prevMenuItem.setChecked(false);
} else {
binding.bottomNavigation.getMenu().getItem(0).setChecked(false);
}
binding.bottomNavigation.getMenu().getItem(position).setChecked(true);
prevMenuItem = binding.bottomNavigation.getMenu().getItem(position);
}
});
binding.viewpager.setAdapter(adapter);
}
MainActivityViewPager
public class MainActivityViewPager extends FragmentStateAdapter {
public MainActivityViewPager(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle) {
super(fragmentManager, lifecycle);
}
@NonNull
@Override
public Fragment createFragment(int position) {
switch (position) {
case 0:
return new HomeFragment();
case 1:
return new ProgressFragment();
case 2:
return new MoreFragment();
case 3:
return new ProfileFragment();
}
return null;
}
@Override
public int getItemCount() {
return 4;
}
Can anyone suggest me a solution? This is currently happening in a production app and I have got red alert on my head. Thank you people
basing on log your ViewPager
is placed inside (nested?) Fragment
, so you should use getChildFragmentManager
instead of getSupportFragmentManager