问题:每当我浏览我的BottomNavigation时,“onCreateView”只在我的绿色子片段上第一次被触发一次。然而,它在我的ParentFragment上工作得很完美。
红色是BottomNavigation的主Activity。蓝色是ParentFragment,里面有ViewPage。绿色是ChildFragment,它根据日期而变化。所以如果我向右滑动,我会得到“8月30日”的不同时间。
现在,如果我导航到“设置部分”,然后再次导航到“主页部分,”“onCreateView”仅在蓝色ParentFragment上触发,而不在绿色ChildFragment上触发。但是,我希望实现的是,每次在蓝色ParentFragment上触发“onCreateView”时,它也应在绿色ChildFragment上触发。如果我将“OffscreenPageLimit设置为1时,它也应该在ChildFragment左右的Fragments上触发。我找不到解决问题的方法。
这是我的蓝色ParentFragment的代码片段:
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(requireActivity());
ViewPager2 viewPager = binding.viewPager;
viewPager.setAdapter(sectionsPagerAdapter);
viewPager.setCurrentItem(1000, false);
viewPager.post(new Runnable() {
public void run() {
// always start at item 1000, so I can swipe left to previous days and swipe right to next days
viewPager.setCurrentItem(1000, false);
//notifyDataSetChanged doesnt trigger "onCreateView" sadly
sectionsPagerAdapter.notifyDataSetChanged();
}
});
viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
// If I swipe right Date changes to August 30 and vice versa it changes to August 28
LocalDate pagerdate = LocalDate.now();
LocalDate days = pagerdate.plusDays(position - 1000);
String month2 = days.getMonth().getDisplayName(TextStyle.FULL, Locale.getDefault());
String dayOfMonth2 = String.valueOf(days.getDayOfMonth());
String monthAndDay2 = month2 + " " + dayOfMonth2;
monthDayText.setText(monthAndDay2);
}
});
viewPager.setOffscreenPageLimit(1);
这是我的适配器的代码:
public class SectionsPagerAdapter extends FragmentStateAdapter {
public SectionsPagerAdapter(@NonNull FragmentActivity fragmentActivity) {
super(fragmentActivity);
}
@Override
public int getItemCount() {
// I have 2000 items to "pretend" to have unlimited items because nobody will swipe 1000 times to the left or right side
return 2000;
}
@NonNull
@Override
public Fragment createFragment(int position) {
LocalDate pagerdate = LocalDate.now();
LocalDate days = pagerdate.plusDays(position - 1000);
//I am passing the date to my Fragment because the time is set according to the date
return TabTodayFragment.newInstance(days.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
}
}
1条答案
按热度按时间au9on6nz1#
如果有人有同样的问题,我找到了解决方案。我用
现在它工作得很好!