我搜索了很多网站(还有stackoverflow),但不明白如何在没有操作栏的情况下实现导航抽屉。我知道这个问题已经在这里被问过,但没有正确的解释和代码。我是 Android 开发的初学者,所以任何人都可以用代码解释我如何制作没有操作栏的导航抽屉
提前致谢!
只需像 @mohan 一样添加您的
DrawerLayout
,然后如果您有一个按钮或点击的东西并想要打开抽屉,只需这样做:
drawer.openDrawer(Gravity.LEFT);
并关闭:
drawer.closeDrawer(Gravity.LEFT);
从示例 Android NavigationDrawer 应用程序开始:
创建一个按钮并在clickListener中调用:
drawer.openDrawer(Gravity.LEFT);
假设您在主要活动中定义了一个图像视图,然后只需向其添加侦听器
activity_main.xml
<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_height="match_parent"
android:layout_width="match_parent"
android:fitsSystemWindows="true"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/background"
android:paddingTop="32dp"
tools:context=".MainActivity"
tools:ignore="HardcodedText">
<ImageView
android:id="@+id/menu_Image"
android:layout_width="32dp"
android:layout_height="32dp"
android:src="@drawable/app_icon"
android:layout_marginTop="16dp"
android:layout_marginStart="16dp"
android:contentDescription="menuIcon" />
</RelativeLayout>
<com.google.android.material.navigation.NavigationView
android:id="@+id/drawerMenu"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/navdrawer_header"
android:background="@color/background"
app:itemTextColor="@color/textMain"
/>
</androidx.drawerlayout.widget.DrawerLayout>
MainActivity.kt
val drawerLayout = findViewById(R.id.drawerLayout)
val menuImage = findViewById(R.id.menu_Image)
menuImage.setOnClickListener{
drawerLayout.openDrawer(GravityCompat.START)
}
提供的代码对我有用