这里使用的是md的NavigationView配合DrawerLayout完成侧滑效果。
布局文件如下所示,drawerlayout作为最外面的布局,第一个布局是主页面布局,第二个则是侧滑栏的布局。

其中headerLayout是侧滑栏的头部,头部布局如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="200dp"
android:background="@drawable/bg_nav_header"
>
<ImageView
android:id="@+id/iv_header"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@drawable/icon_my2"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp"
/>
<TextView
android:id="@+id/tv_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/iv_header"
android:layout_centerHorizontal="true"
android:layout_marginTop="8dp"
android:textColor="@color/white"
android:textSize="@dimen/ts_primary"
/>
</RelativeLayout>
menu指的是侧滑栏下面的选项列表,这个需要在res中新建一个menu文件夹,然后填写自己需要的信息,menu信息如下:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/nav_change_pwd"
android:icon="@drawable/icon_change_pwd"
android:title="修改密码"
android:iconTint="@color/theme_primary"
/>
<item
android:id="@+id/nav_exit"
android:icon="@drawable/icon_exit"
android:title="退出"
android:iconTint="@color/black"
/>
</menu>
然后添加侧滑栏列表的点击事件:
nv.setNavigationItemSelectedListener(this);
这样就基本完成了侧滑功能,效果如图所示:

注意点:
1.侧滑列表的图标默认是灰色的,如果需要用图片自己的颜色,需要在代码中设置
nv.setItemIconTintList(null);,注意在xml中设置不管用。 如果想自定义图片和字体颜色,可以在NavigationView中通过
app:itemTextColor="@color/black" app:itemIconTint="@color/black"
批量修改的,也可以在menu的item中通过
android:iconTint="@color/black"设置单个图片的颜色,使用这个需要nv.setItemIconTintList(null);。
2.NavigationView需要在布局文件的最下面,就是NavigationView下面不能有别的控件,否则点击事件可能会无效。

本文详细介绍如何使用MD的NavigationView配合DrawerLayout实现侧滑菜单效果。包括布局文件配置、菜单项自定义及点击事件添加,同时解决图标颜色及布局位置问题。
281

被折叠的 条评论
为什么被折叠?



