Jetpack

jetpack navigation不复用fragment的问题

2020-09-10  本文已影响0人  三月四晴
快速创建一个Navigation项目 直接在Android studio中创建一个Navigation界面的activity 工具就帮我们创建好了 image.png
在运行跑项目的时候发现- -切换了下fragment 上一个界面的fragment 已经被销毁了查了下资料发现这个其实不是bug而是特定这么设计的 翻了下源码 发现FragmentNavigator 中navigate方法是直接用Fragment的replace把fragment进行了替换 image.png
既然知道为啥切换fragment 会被销毁的原因了 那么解决方案就出来了

把 replace 换成 show和hide 就行了

废话不多说 直接上代码 写一个类继承FragmentNavigator 重写 navigate方法
@Navigator.Name("fixFragment")  //fix 5: 需要指定1个名字,源码里自带的名字有navigation、activity、fragment、dialog
public class FixFragmentNavigator extends FragmentNavigator {
    private static final String TAG = "FixFragmentNavigator";
    private Context mContext;
    private FragmentManager mFragmentManager;
    private int mContainerId;

    public FixFragmentNavigator(@NonNull Context context, @NonNull FragmentManager manager, int containerId) {
        super(context, manager, containerId);
        mContext = context;
        mFragmentManager = manager;
        mContainerId = containerId;
    }

    @Nullable
    @Override
    public NavDestination navigate(@NonNull Destination destination, @Nullable Bundle args, @Nullable NavOptions navOptions, @Nullable Navigator.Extras navigatorExtras) {
        if (mFragmentManager.isStateSaved()) {
            Log.i(TAG, "Ignoring navigate() call: FragmentManager has already"
                    + " saved its state");
            return null;
        }
        String className = destination.getClassName();
        if (className.charAt(0) == '.') {
            className = mContext.getPackageName() + className;
        }
        //fix 1: 把类名作为tag,寻找已存在的Fragment
        //(如果想只针对个别fragment进行保活复用,可以在tag上做些标记比如加个前缀)
        Fragment frag = mFragmentManager.findFragmentByTag(className);
        if (null == frag) {
            //不存在,则创建
            frag = instantiateFragment(mContext, mFragmentManager, className, args);
        }

        frag.setArguments(args);
        final FragmentTransaction ft = mFragmentManager.beginTransaction();

        int enterAnim = navOptions != null ? navOptions.getEnterAnim() : -1;
        int exitAnim = navOptions != null ? navOptions.getExitAnim() : -1;
        int popEnterAnim = navOptions != null ? navOptions.getPopEnterAnim() : -1;
        int popExitAnim = navOptions != null ? navOptions.getPopExitAnim() : -1;
        if (enterAnim != -1 || exitAnim != -1 || popEnterAnim != -1 || popExitAnim != -1) {
            enterAnim = enterAnim != -1 ? enterAnim : 0;
            exitAnim = exitAnim != -1 ? exitAnim : 0;
            popEnterAnim = popEnterAnim != -1 ? popEnterAnim : 0;
            popExitAnim = popExitAnim != -1 ? popExitAnim : 0;
            ft.setCustomAnimations(enterAnim, exitAnim, popEnterAnim, popExitAnim);
        }

//        ft.replace(mContainerId, frag);
        //fix 2: replace换成show和hide
        List<Fragment> fragments = mFragmentManager.getFragments();
        for (Fragment fragment : fragments) {
            ft.hide(fragment);
        }
        if (!frag.isAdded()) {
            ft.add(mContainerId, frag, className);
        }
        ft.show(frag);
        ft.setPrimaryNavigationFragment(frag);

        final @IdRes int destId = destination.getId();

        //fix 3: mBackStack是私有的,而且没有暴露出来,只能反射获取
        ArrayDeque<Integer> mBackStack;
        try {
            Field field = FragmentNavigator.class.getDeclaredField("mBackStack");
            field.setAccessible(true);
            mBackStack = (ArrayDeque<Integer>) field.get(this);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        final boolean initialNavigation = mBackStack.isEmpty();
        final boolean isSingleTopReplacement = navOptions != null && !initialNavigation
                && navOptions.shouldLaunchSingleTop()
                && mBackStack.peekLast() == destId;

        boolean isAdded;
        if (initialNavigation) {
            isAdded = true;
        } else if (isSingleTopReplacement) {
            if (mBackStack.size() > 1) {
                mFragmentManager.popBackStack(
                        generateBackStackName(mBackStack.size(), mBackStack.peekLast()),
                        FragmentManager.POP_BACK_STACK_INCLUSIVE);
                ft.addToBackStack(generateBackStackName(mBackStack.size(), destId));
            }
            isAdded = false;
        } else {
            ft.addToBackStack(generateBackStackName(mBackStack.size() + 1, destId));
            isAdded = true;
        }
        if (navigatorExtras instanceof Extras) {
            Extras extras = (Extras) navigatorExtras;
            for (Map.Entry<View, String> sharedElement : extras.getSharedElements().entrySet()) {
                ft.addSharedElement(sharedElement.getKey(), sharedElement.getValue());
            }
        }
        ft.setReorderingAllowed(true);
        ft.commit();
        if (isAdded) {
            mBackStack.add(destId);
            return destination;
        } else {
            return null;
        }
    }

    //fix 4: 从父类那边copy过来即可
    @NonNull
    private String generateBackStackName(int backStackIndex, int destId) {
        return backStackIndex + "-" + destId;
    }
}
下面是activity的代码
public class MainActivity extends AppCompatActivity {
    private TextView text;
    private TestViewModel viewModel;
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main5);
//        text = findViewById(R.id.text);
//        BottomNavigationView navView = findViewById(R.id.nav_view);
//        // Passing each menu ID as a set of Ids because each
//        // menu should be considered as top level destinations.
//        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
//                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
//                .build();
//        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
//        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
//        NavigationUI.setupWithNavController(navView, navController);
//        viewModel = new ViewModelProvider(this).get(TestViewModel.class);
//        viewModel.name.observe(this, new Observer<String>() {
//            @Override
//            public void onChanged(String s) {
//                text.setText(s);
//            }
//        });
//    }

    BottomNavigationView navView;
    NavController navController;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main5);
        text = findViewById(R.id.text);
        navView = findViewById(R.id.nav_view);
        viewModel = new ViewModelProvider(this).get(TestViewModel.class);
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
        //获取导航控制器
        navController = NavHostFragment.findNavController(fragment);
        //创建自定义的Fragment导航器
        FixFragmentNavigator fragmentNavigator =
                new FixFragmentNavigator(this, fragment.getChildFragmentManager(), fragment.getId());
        //获取导航器提供者
        NavigatorProvider provider = navController.getNavigatorProvider();
        //把自定义的Fragment导航器添加进去
        provider.addNavigator(fragmentNavigator);
        //手动创建导航图
        NavGraph navGraph = initNavGraph(provider, fragmentNavigator);
        //设置导航图
        navController.setGraph(navGraph);
        //底部导航设置点击事件
        navView.setOnNavigationItemSelectedListener(item -> {
            navController.navigate(item.getItemId());
            return true;
        });

        viewModel.name.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                text.setText(s);
            }
        });
    }

    //手动创建导航图,把3个目的地添加进来
    private NavGraph initNavGraph(NavigatorProvider provider, FixFragmentNavigator fragmentNavigator) {
        NavGraph navGraph = new NavGraph(new NavGraphNavigator(provider));

        //用自定义的导航器来创建目的地
        FragmentNavigator.Destination destination1 = fragmentNavigator.createDestination();
        destination1.setId(R.id.navigation_home);
        destination1.setClassName(HomeFragment.class.getCanonicalName());
        destination1.setLabel(getResources().getString(R.string.title_home));
        navGraph.addDestination(destination1);

        FragmentNavigator.Destination destination2 = fragmentNavigator.createDestination();
        destination2.setId(R.id.navigation_dashboard);
        destination2.setClassName(DashboardFragment.class.getCanonicalName());
        destination2.setLabel(getResources().getString(R.string.title_dashboard));
        navGraph.addDestination(destination2);

        FragmentNavigator.Destination destination3 = fragmentNavigator.createDestination();
        destination3.setId(R.id.navigation_notifications);
        destination3.setClassName(NotificationsFragment.class.getCanonicalName());
        destination3.setLabel(getResources().getString(R.string.title_notifications));
        navGraph.addDestination(destination3);

        navGraph.setStartDestination(R.id.navigation_home);

        return navGraph;
    }

    /**
     * 重写返回键事件
     * fix: ComponentActivity.onBackPressed -> ... -> NavController.popBackStack()
     * 自定义导航器后,会引起NavController管理的回退栈出问题
     */
    @Override
    public void onBackPressed() {
        int currentId = navController.getCurrentDestination().getId();
        int startId = navController.getGraph().getStartDestination();
        //如果当前目的地不是HomeFragment,则先回到HomeFragment
        if (currentId != startId) {
            navView.setSelectedItemId(startId);
        } else {
            finish();
        }
    }
}
参考:Android-Jetpack笔记-Navigation之Fragment支持复用
上一篇下一篇

猜你喜欢

热点阅读