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);
});
}
+V why_null 请备注:from博客园