()实现侧滑(Navigation Drawer)
之前左侧拉出 Drawer Menu 是一个空白的面板。以前需要用LinearLayout 或者 ListView 去实现,这种方式是非常麻烦的。现在可以采用NavigationView来实现,NavigationView 就是为了 Drawer Menu 而特别设计的。
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
.......
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="@+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/nav_header"
app:itemBackground="@android:color/holo_red_dark"
app:itemTextColor="#FFFF00"
app:menu="@menu/navigation_drawer_items" />
</android.support.v4.widget.DrawerLayout>
itemBackground — 设置菜单项的背景
itemTextColor — 设置菜单项的文本颜色
其中headerLayout是标题布局文件,menu是菜单资源文件。NavigationView 将这两个资源文件绑定起来,作为 Drawer Menu 的菜单区域。
通过声明 setNavigationItemSelectedListener 来监听NavigationView菜单项的点击事件
NavigationView控件.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id) {
case R.id.XX:
........
break;
case R.id.XX:
........
break;
case R.id.XX:
........
break;
}
return false;
}
});