android - 无法通过按钮单击打开导航抽屉(仅通过手势)
问题描述
我可以通过手势显示导航抽屉,但不能通过按钮单击。用工具栏试过了,还是不行。有任何想法吗?
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;
}
解决方案
尝试使用标志,
mDrawerLayout.openDrawer(Gravity.LEFT);
mDrawerLayout.closeDrawer(Gravity.LEFT);
详细参考这里的代码
你会分享 setNavigationItemSelectedListener 的实现吗?您可能没有正确返回布尔值。
推荐阅读
- ruby - ruby 拆分后如何计算长度,除了字符串中的一些值?
- ruby-on-rails - Ruby graphql 解析器替代方案:方法挂钩 --- 它是如何工作的?
- reactjs - 在函数组件中使用带有注入和观察者的钩子 - mobx
- python - 如何在 Linux 中拦截中键粘贴事件?
- pyspark - Databricks-Connect 6.6 不向 Spark 上下文添加自定义模块
- php - 如何使用 Php -S 模拟 URL 的文件目录?
- python - 在python中读取图像时出现内存错误
- python - 如何在某个索引后更改列表组的元素?
- sql - 在单个过程中对 scope_identity() 进行两次或多次调用是否有效?
- json - 如何从无效的 json 中验证和删除不需要的字符串