使用导航组件来回导航时,ViewPager 的内容会消失



将导航迁移到新的 Jetpack 导航组件后,我发现在使用库来回导航后,ViewPager 中前两个片段的内容/布局消失了。单击选项卡后,它会回来。

起初我以为这是因为我在logcat中看到的错误,但是修复它们后,问题仍然存在。

这是我的主活动代码:

private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    bindResources();
    // Setup Toolbar & Navigation Component
    setSupportActionBar(toolbar);
    setupNavigation();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_options, menu);
    return super.onCreateOptionsMenu(menu);
}
private void setupNavigation() {
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph())
            .setDrawerLayout(drawerLayout)
            .build();
    NavigationUI.setupWithNavController(toolbar, navController, appBarConfiguration);
    NavigationUI.setupWithNavController(navigationView, navController);
}

这是我的ViewPagerAdapter的代码:

private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(@NonNull FragmentManager fm) {
    super(fm);
}
public void addFragment(@NonNull Fragment fragment, String title) {
    fragmentList.add(fragment);
    fragmentTitleList.add(title);
}
@NonNull
@Override
public Fragment getItem(int position) {
    return fragmentList.get(position);
}
@Override
public int getCount() {
    return fragmentList.size();
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
    return fragmentTitleList.get(position);
}

这是我的主页片段:

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    bindResources(view);
    // ViewPager
    ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
    viewPagerAdapter.addFragment(new TodayFragment(), getString(R.string.tab_today_title));
    viewPagerAdapter.addFragment(new PriorityFragment(), getString(R.string.tab_priority_title));
    viewPagerAdapter.addFragment(new PlannedFragment(), getString(R.string.tab_planned_title));
    viewPagerAdapter.addFragment(new TasksFragment(), getString(R.string.tab_tasks_title));
    viewPager.setAdapter(viewPagerAdapter);
    // TabLayout
    tabLayout.setupWithViewPager(viewPager);
}

Java:我通过替换解决了这个问题

= new ViewPagerAdapter(getActivity().getSupportFragmentManager());

= new ViewPagerAdapter(getChildFragmentManager());

Kotlin:通过替换

= ViewPagerAdapter(fragmentManager)

= ViewPagerAdapter(childFragmentManager)

相关内容

  • 没有找到相关文章

最新更新