1. 程式人生 > >android 側滑選單

android 側滑選單

這裡使用的是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下面不能有別的控制元件,否則點選事件可能會無效。