废话少说,直接记录步骤。
在app的build.gradle中添加
compile 'com.android.support:design:26.1.0'
这里注意一下:design:26.1.0 是和 implementation 'com.android.support:appcompat-v7:26.1.0'的版本一致的
使用实例,准备工作:新建一个menu组和一个header布局
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/menu_1" android:title="应用管理" /> <item android:id="@+id/menu_2" android:title="消息中心" /> </menu>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@mipmap/ic_launcher"/> </LinearLayout>
Activity布局:
<?xml version="1.0" encoding="utf-8"?> <android.support.v4.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:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/drawer_layout" tools:context="com.mvp.org.view.DrawerLayoutUse"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="测试"/> </LinearLayout> <!--侧滑菜单--> <!--android:layout_gravity="start"表示从左到右滑出,end表示从右到左--> <LinearLayout android:layout_width="320dp" android:layout_height="match_parent" android:background="@color/blue_btn_bg_pressed_color" android:layout_gravity="end"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:text="测试TextView"/> </LinearLayout> <android.support.design.widget.NavigationView android:id="@+id/design_navigation_view" android:layout_width="320dp" android:layout_height="match_parent" app:headerLayout="@layout/header" app:menu="@menu/menu_left" android:layout_gravity="start"> </android.support.design.widget.NavigationView> </android.support.v4.widget.DrawerLayout>
逻辑代码以及绑定事件
class DrawerLayoutUse : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_drawer_layout) val view: View = design_navigation_view.getHeaderView(0) view.setOnClickListener{ Log.e("DrawerLayoutUse","头部点击") } design_navigation_view.setNavigationItemSelectedListener({ item -> when (item.itemId) { R.id.menu_1 -> { val alertTool = AlertDialogUtils(this) alertTool.AlertTitleAndMessage("点击","按钮①","success") } R.id.menu_2 -> { val alertTool = AlertDialogUtils(this) alertTool.AlertTitleAndMessage("点击","按钮②","success") } } false }) } }