我正在尝试在一个特定的片段中实现导航抽屉,虽然显示了导航抽屉图标,但是当我单击它时,它无法打开或关闭导航抽屉。PS:导航抽屉可用于滑动。
我的代码如下:
该片段的XML布局
<?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:background="#7BC4CD"
tools:context=".ui.ListFragment">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:itemCount="5"
tools:listitem="@layout/user_item" />
</androidx.constraintlayout.widget.ConstraintLayout>
<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/nav_drawer_menu" />
</androidx.drawerlayout.widget.DrawerLayout>
Fragment类的代码如下:
class ListFragment : Fragment(R.layout.fragment_list){
lateinit var toggle:ActionBarDrawerToggle
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
toggle= ActionBarDrawerToggle(this.activity,drawerLayout, R.string.open, R.string.close)
drawerLayout.addDrawerListener(toggle)
toggle.syncState()
(requireActivity() as MainActivity).supportActionBar?.setDisplayHomeAsUpEnabled(true)
nav_view.setNavigationItemSelectedListener {
when(it.itemId){
R.id.menu_item_logout -> Navigation.findNavController(view).navigate(R.id.action_listFragment_to_registerFragment)
}
true
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if(toggle.onOptionsItemSelected(item)){
return true
}
return super.onOptionsItemSelected(item)
}
}
还要注意,我正在使用导航组件
任何帮助都会很棒