Android片段重复使用BottomNavigationView

时间:2017-06-24 13:47:24

标签: android android-fragments bottomnavigationview

我的应用程序主要内容由3个FragmentsBottomNavigationView中的1个组成,有3个选项。 BottomNavigationView上的每个按钮都会使用3个Fragments中的一个切换主要内容。

在切换Fragments的方法中,我发现标记已经存在Fragment。如果是,我不创建新实例但使用现有实例:

    private void switchToDailyFragment(int fragmentArgument) {

    FragmentManager manager = getSupportFragmentManager();
    Fragment dailyFragment = manager.findFragmentByTag(String.valueOf(TrainingFragment.MODE_DAY));

    if (dailyFragment == null) {
        dailyFragment = TrainingFragment.newInstance(fragmentArgument);
        Log.d(TAG, "switchToDailyFragment: no instance of monthly fragment, making instance now");
    }

    manager.beginTransaction()
            .setCustomAnimations(R.anim.fade_in, R.anim.fade_out)
            .replace(R.id.main_content, dailyFragment, String.valueOf(TrainingFragment.MODE_DAY))
            .commit();

}

我设置静态计数器变量,每次调用newInstance(int mode)的工厂方法Fragment时,该变量都会递增:

  public static int instanceCount = 0;

并按如下方式递增:

    public static TrainingFragment newInstance(int mode) {
    instanceCount++;
    Log.d(TAG, "newInstance: instace count: " + instanceCount);
    TrainingFragment fragment = new TrainingFragment();
    fragment.setMode(mode);
    return fragment;
}

所以我想它的设置方式,它应该为Fragment中的每个按钮创建最多3个BottomNavigationView个实例,然后重用这些实例。 但是,即使根据日志已经有3个实例,每次选择项目时都会创建更多实例:

 D/TrainingFragment: newInstance: instace count: 1
 D/TrainingFragment: newInstance: instace count: 2
 D/TrainingFragment: newInstance: instace count: 3
 D/TrainingFragment: newInstance: instace count: 4
 D/TrainingFragment: newInstance: instace count: 5
 D/TrainingFragment: newInstance: instace count: 6
 D/TrainingFragment: newInstance: instace count: 7
 D/TrainingFragment: newInstance: instace count: 8
 and so on

这是正常行为还是我做错了什么?

0 个答案:

没有答案