DrawerLayout可以实现左滑和右滑功能,只要在layout文件中配置好左右两个抽屉就可以了,左右两个抽屉可以是任意的view,结合NavigationView可以很好实现侧滑菜单的功能
要使用DrawerLayout,需要v4包,使用NavigationView,需要v7包
实例:
上面的效果可以很容易的实现,其主要体现在布局上:
一、主布局文件
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.qf.drawlayouttest.MainActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<android.support.design.widget.NavigationView
android:id="@+id/nvLeft"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="left"//表示左滑 ,如果设置为right则表示右滑
app:headerLayout="@layout/layout_nvhead"
app:menu = "@menu/mymenu"
/>
</android.support.v4.widget.DrawerLayout>
二、给抽屉添加一个标题头的布局:
headerLayout就是给导航栏增加一个头部Layout。
menu就是对应菜单项的选择条目。
navigation_header.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#24B1F5">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="text"
android:textSize="50dp"
android:textColor="#ffffff"
/>
</RelativeLayout>
三、给抽屉添加对应菜单项的选择条目:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="@+id/item_one"
android:icon="@mipmap/icon"
android:title="我的动态"></item>
<item
android:id="@+id/item_two"
android:icon="@mipmap/icon"
android:title="我的留言"></item>
<item
android:id="@+id/item_three"
android:icon="@mipmap/icon"
android:title="附近的人"></item>
</group>
</menu>
四、设置navigationview的菜单响应:
//设置导航栏NavigationView的点击事件
NavigationView mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.item_one:
getSupportFragmentManager().beginTransaction().replace(R.id.frame_content, new FragmentOne()).commit();
mToolbar.setTitle("我的动态");
break;
case R.id.item_two:
getSupportFragmentManager().beginTransaction().replace(R.id.frame_content, new FragmentTwo()).commit();
mToolbar.setTitle("我的留言");
break;
case R.id.item_three:
getSupportFragmentManager().beginTransaction().replace(R.id.frame_content, new FragmentThree()).commit();
mToolbar.setTitle("附近的人");
break;
}
menuItem.setChecked(true);//点击了把它设为选中状态
mDrawerLayout.closeDrawers();//关闭抽屉
return true;
}
});
一个抽屉的简单实现大概就是这些步骤,具体的实现功能,也就和这个技术关系不大。代码该咋写,还得咋写。之前看到QQ,还有csdn的APP,还有很多APP多使用了这种技术,当时觉得很拗的样子,现在觉得也就是那么回事。