使用 Android 导航组件隐藏抽屉项目
Hiding Drawer item Using Android Navigation Component
我正在使用导航组件和导航抽屉。如果用户在我的 LoginFragment
中使用 FirebaseAuth 登录,我想从导航抽屉中隐藏 login/signup 菜单。
谁能告诉我该怎么做?
If a user login with FirebaseAuth in my LoginFragment I want to hide login/signup menu from navigation drawer
您可以从附加到导航抽屉的 NavigationView
中获取菜单并使用 removeItem(id)
删除特定项目:
if (userLoggedIn) { // Set that to your logic when the user logged in.
removeItem(R.id.singup); // adjust that to the id you set to sign up
removeItem(R.id.login); // adjust that to the id you set to login
}
public removeItem(int id) {
NavigationView navView = findViewById(R.id.foo); // Add your NavigationView id
Menu menu = navView.getMenu();
if (menu.findItem(id) != null) // Make sure that the item exists in the menu
menu.removeItem(id);
}
更新
navigation drawer is in my MainActivity
要从片段中访问 activity,请使用 requireActivity()
或 getActivity()
,例如:
((MainActivity) requireActivity()).removeItem(R.id.login); // adjust that to the id you set to sign up
((MainActivity) requireActivity()).removeItem(R.id.signup); // adjust that to the id you set to login
好的,我已经解决了这个问题。
当用户通过 LoginFragment 登录时,我会重新加载 MainActivity。
当用户再次通过 Navigation Drawer 注销时,我再次重新加载 MainAcitvity。
startActivity(new Intent(getActivity(), MainActivity.class)); getActivity().finish();
我正在使用导航组件和导航抽屉。如果用户在我的 LoginFragment
中使用 FirebaseAuth 登录,我想从导航抽屉中隐藏 login/signup 菜单。
谁能告诉我该怎么做?
If a user login with FirebaseAuth in my LoginFragment I want to hide login/signup menu from navigation drawer
您可以从附加到导航抽屉的 NavigationView
中获取菜单并使用 removeItem(id)
删除特定项目:
if (userLoggedIn) { // Set that to your logic when the user logged in.
removeItem(R.id.singup); // adjust that to the id you set to sign up
removeItem(R.id.login); // adjust that to the id you set to login
}
public removeItem(int id) {
NavigationView navView = findViewById(R.id.foo); // Add your NavigationView id
Menu menu = navView.getMenu();
if (menu.findItem(id) != null) // Make sure that the item exists in the menu
menu.removeItem(id);
}
更新
navigation drawer is in my MainActivity
要从片段中访问 activity,请使用 requireActivity()
或 getActivity()
,例如:
((MainActivity) requireActivity()).removeItem(R.id.login); // adjust that to the id you set to sign up
((MainActivity) requireActivity()).removeItem(R.id.signup); // adjust that to the id you set to login
好的,我已经解决了这个问题。 当用户通过 LoginFragment 登录时,我会重新加载 MainActivity。 当用户再次通过 Navigation Drawer 注销时,我再次重新加载 MainAcitvity。
startActivity(new Intent(getActivity(), MainActivity.class)); getActivity().finish();