I want to create a drawable menu for my android app, currently using Java. I followed this tutorial: https://www.geeksforgeeks.org/navigation-drawer-in-android/
Mainactivity.java
...
public DrawerLayout drawerLayout;
public ActionBarDrawerToggle actionBarDrawerToggle;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// drawer layout instance to toggle the menu icon to open
// drawer and back button to close drawer
drawerLayout = findViewById(R.id.my_drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.nav_open, R.string.nav_close);
// pass the Open and Close toggle for the drawer layout listener
// to toggle the button
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
// to make the Navigation drawer icon always appear on the action bar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
Toast.makeText(getApplicationContext(), "funciona", Toast.LENGTH_SHORT).show();
if (actionBarDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
switch (item.getItemId()) {
case R.id.firstitem:
Toast.makeText(getApplicationContext(), "obre", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
activity_main.xml There is a big relativeLayout and some linearLayouts, at the very end, this code:
<com.google.android.material.navigation.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/navigation"
android:fitsSystemWindows="true"
/>
</androidx.drawerlayout.widget.DrawerLayout>
navigation.xml
<?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:ignore="HardcodedText">
<item
android:id="@+id/firstitem"
android:title="first item" />
<item
android:id="@+id/seconditem"
android:title="Second item" />
</menu>
The code does compile, opens the menu and shows the first Toast ("funciona"), options are highlighted when you press them but nothing shows up. I wanted to open a new activity but I can't get the new Toast ("obre") to show up. It's seems like there is something missing with the switch case and I can't figure it out. I tried using the if-else, to no avail.
Thank you
onOptionsItemSelected()
method. To listen for clicks on the items in the drawer, you would need to set anOnNavigationItemSelectedListener
on theNavigationView
, something like is shown in this answer.