Android 动态改变 navigation 的 startDestination, 使得已登录的用户直接跳过 LoginFragment

需求:

  • 未登录用户打开 App,会展示登录页面 LoginFragment
  • 已登录用户打开 App,直接展示 MainFragment

nav_graph.xml 结构如下:

MainActivity.java:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        // 已经登录了
        if (Utils.isLoggedIn()) {
            NavGraph graph = navController.getGraph();
            graph.setStartDestination(R.id.MainFragment);
            navController.setGraph(graph);
        }
        appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
        NavigationUI.setupActionBarWithNavController(this, navController);
    }

LoginFragment.java:

    void onLoginSuccess() {
        new Handler(Looper.getMainLooper()).post(() -> {
                AppCompatActivity activity = (AppCompatActivity)getActivity();
                if (actitivy == null) return;
                NavOptions navOptions = new NavOptions.Builder()
                        .setPopUpTo(R.id.LoginFragment, true)
                        .build();
                NavController navController = NavHostFragment.findNavController(this);
                NavGraph graph = navController.getGraph();
                graph.setStartDestination(R.id.MainFragment);
                navController.setGraph(graph);
                NavigationUI.setupActionBarWithNavController(activity, navController);
                navController.navigate(R.id.action_LoginFragment_to_MainFragment, null, navOptions);
        });
    }

https://stackoverflow.com/a/53017625

posted on 2023-05-18 15:18  明天有风吹  阅读(517)  评论(0编辑  收藏  举报

导航

+V atob('d2h5X251bGw=')

请备注:from博客园