TabLayout 是如何工作的?

How does TabLayout work?

我的 MainActivity 里面有一个 Tablayout 和一个显示三个片段的 Viewpager

当应用程序启动时,会发生这种情况:

onCreate Fragment 1
onCreate Fragment 1
onActivityCreated Fragment 1
onResume Fragment 1
onActivityCreated Fragment 2
onResume Fragment 2

点击第二个标签时会发生这种情况:

onCreate Fragment 1
onActivityCreated Fragment 3
onResume Fragment 3

点击第三个标签:

onSaveInstanceState Fragment 1

从第三个标签点击第二个标签:

onCreate Fragment 1
onActivityCreated Fragment 1
onResume Fragment 1

代码

public class ViewPagerAdapter extends FragmentStatePagerAdapter {

private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();

public ViewPagerAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int position) {
    return mFragmentList.get(position);
}

@Override
public int getCount() {
    return mFragmentList.size();
}

@Override
public CharSequence getPageTitle(int position) {
    return mFragmentTitleList.get(position);
}

public void addFragment(Fragment fragment, String title) {
    mFragmentList.add(fragment);
    mFragmentTitleList.add(title);
}
}

在 MainActivity 中

        viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tablayout);
    tabLayout.setupWithViewPager(viewPager);
}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(DishFragment.newInstance(1), "Кулинария");
    adapter.addFragment(DishFragment.newInstance(2), "Кондитерская");
    adapter.addFragment(DishFragment.newInstance(3), "Хлебобулочная");
    viewPager.setAdapter(adapter);
}

onCreate 片段 1
onCreate 片段 1
onActivityCreated 片段 1
onResume 片段 1
onActivityCreated 片段 2
onResume 片段 2

onCreate 片段 1
onActivityCreated 片段 3
onResume 片段 3

onSaveInstanceState 片段 1

onCreate 片段 1
onActivityCreated 片段 1
onResume 片段 1

ViewPager 将相邻的 Fragment 保存在内存中,以便在页面之间快速转换。我在想重新创建的片段有一个修复程序(因为您将它们存储在列表中,所以不要自己多次创建它们)。

When app started this process happens:

我不确定加倍的 onCreate #1,但片段 1 和片段 2 已启动

onCreate Fragment 1
onCreate Fragment 1
onActivityCreated Fragment 1
onResume Fragment 1
onActivityCreated Fragment 2
onResume Fragment 2

This happens when tapping at second tap:

片段 1 和 2 已创建,但片段 3 现在已创建

onCreate Fragment 1
onActivityCreated Fragment 3
onResume Fragment 3

Tapping at third tap:

OS 不再需要保留片段 1

onSaveInstanceState Fragment 1

Tapping on second tap from third tap:

片段 1 已创建/恢复

onCreate Fragment 1
onActivityCreated Fragment 1
onResume Fragment 1