How to change my activity_main_drawer visibility in layout based on the Using SessionManager condition
Here's an example of how to change the visibility of a navigation drawer item based on a condition:
activity_main_drawer.xml Code
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
<group android:checkableBehavior="single">
<item
android:id="@+id/nav_home"
android:icon="@drawable/ic_menu_camera"
android:title="@string/menu_home" />
<item
android:id="@+id/nav_gallery"
android:icon="@drawable/ic_menu_gallery"
android:title="@string/menu_gallery" />
<item
android:id="@+id/nav_slideshow"
android:icon="@drawable/ic_menu_slideshow"
android:title="@string/menu_slideshow" />
<item
android:id="@+id/nav_UserProfile"
android:icon="@drawable/ic_menu_slideshow"
android:title="@string/menu_userProfile" />
</group>
</menu>
MainActivity.Java Code
public class MainActivity extends AppCompatActivity {
SessionManager sessionManager;
private AppBarConfiguration mAppBarConfiguration;
private ActivityMainBinding binding;
MenuItem action,reg,home,gallery,slideshow,userprofile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.appBarMain.toolbar);
DrawerLayout drawer = binding.drawerLayout;
NavigationView navigationView = binding.navView;
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,R.id.nav_UserProfile)
.setOpenableLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
sessionManager = new SessionManager(this);
NavigationView navigationViews = findViewById(R.id.nav_view);
Menu menu = navigationViews.getMenu();
MenuItem myMenuItem = menu.findItem(R.id.nav_UserProfile);
if (sessionManager.isLoggedIn()) {
myMenuItem.setVisible(true);
} else {
myMenuItem.setVisible(false);
}
}
Note that you should replace conditionIsTrue
with the actual condition that you want to use. This condition could be based on any variables or data that you want to check.
You can call this code whenever the condition may change, such as in an onResume()
function or in a listener that watches for changes in data or variables. This will update the visibility of the navigation drawer item dynamically based on the condition.