单击按钮无法打开导航抽屉(仅通过手势)

时间:2019-11-05 02:23:18

标签: android navigation-drawer

我可以通过手势显示导航抽屉,但不能通过单击按钮显示。尝试过工具栏,仍然无法正常工作。 有什么想法吗?

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);
}

此外,当通过手势调用抽屉时,永远不会调用onNavigationItemSelected。不知道为什么,一切都准备就绪(我检查了很多教程)。

<?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>

更新:

@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;
}

1 个答案:

答案 0 :(得分:0)

尝试使用标志

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

详细参考stepper widget中的代码

您是否将共享setNavigationItemSelectedListener实现?您可能没有从中正确返回布尔值。