简体   繁体   中英

Unable to open navigation drawer by button click (only by gesture)

I am able to show navigation drawer by gesture, but not through button click. Tried with toolbar, does not work still. Any ideas?

ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.cancel);
toggle.setDrawerIndicatorEnabled(true);
navigation.bringToFront();
drawerLayout.addDrawerListener(toggle);
navigation.setNavigationItemSelectedListener(this);
toggle.syncState();

//code to open on regular button click
if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
    drawerLayout.closeDrawer(GravityCompat.START);
} else {
    drawerLayout.openDrawer(navigation);
}

Also, onNavigationItemSelected is never ever called when drawer is invoked by gesture. Not sure why, everything is in place (I checked many, many tutorials).

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

        <FrameLayout
            android:id="@+id/fragmentContainer"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </FrameLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/navigation_menu" />
</androidx.drawerlayout.widget.DrawerLayout>

Update:

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    Log.d(TAG, "onNavigationItemSelected:");
    if (item.getItemId() == R.id.optionServices) {
        Toast.makeText(MainActivity.this, "optionServices", Toast.LENGTH_SHORT).show();
    }
    return true;
}

Try using flags,

mDrawerLayout.openDrawer(Gravity.LEFT);
mDrawerLayout.closeDrawer(Gravity.LEFT);

Refer code from here in detail

Would you share the setNavigationItemSelectedListener implementation? you may have not returned boolean value from it properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM