cheeroke cheeroke - 12 days ago 5
Android Question

Navigation Menu buttons clickable in Navigation Drawer

I've got to this point of creating navigation drawer where I don't know how to make the buttons clickable from the drawer.

My

MainActivity
:

public class MainActivity extends AppCompatActivity {

private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mDrawerLayout = (DrawerLayout)findViewById(R.id.drawerLayout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.string.open, R.string.close);

mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

if(mToggle.onOptionsItemSelected(item)){

return true;
}
else{
switch (item.getItemId()){
case R.id.nav_menu:
Toast.makeText(MainActivity.this, "Menu!", Toast.LENGTH_SHORT).show();
return true;
case R.id.nav_setings:
Toast.makeText(MainActivity.this, "Settings!", Toast.LENGTH_SHORT).show();
return true;
}
}

return super.onOptionsItemSelected(item);
}
}


Please note that switch statement in
onOptionsItemSelected
doesn't work.

My menu xml looks like this:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@+id/nav_menu"
android:title="My Account"/>
<item android:id="@+id/nav_setings"
android:title="Settings"/>
<item android:id="@+id/nav_logout"
android:title="Log Out"/>

</menu>


So, my question is how to make those items from the drawer clickable?

Answer

Assuming you also have a NavigationView inside your DrawerLayout, you just have to add an OnNavigationItemSelectedListener:

NavigationView navigation = (NavigationView) findViewById(R.id.navigation);

navigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch(item.getItemId()) {
            case R.id.nav_menu:
                // Handle menu click
                return true;
            case R.id.nav_settings:
                // Handle settings click
                return true;
            case R.id.nav_logout:
                // Handle logout click
                return true;
            default:
                return false;
        }
    }
});
Comments