DrawerLayout 是v4的扩展组件,具体使用步骤如下:
1、布局文件内容如下:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--主布局-->
<RelativeLayout
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
<!--左侧滑动菜单-->
<RelativeLayout
android:id="@+id/drawer_left_menu"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start">
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
注:android:layout_gravity="start"
这个属性是必须的。
2、初始化DrawerLayout组件
DrawerLayout mDrawerLayout;
RelativeLayout mDrawerLeftMenu;
ActionBarDrawerToggle mDrawerToggle;
private void setupDrawerLayout() {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLeftMenu = (RelativeLayout) findViewById(R.id.drawer_left_menu);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
@Override
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
}
@Override
public void onDrawerStateChanged(int newState) {
super.onDrawerStateChanged(newState);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
3、在Activity的onCreate(Bundle savedInstanceState)方法中调用
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupDrawerLayout();
}
4、想打开或者关闭左侧菜单的调用下面的方法
public void toggleLeftMenu() {
if (mDrawerLayout.isDrawerOpen(mDrawerLeftMenu)) {
mDrawerLayout.closeDrawer(mDrawerLeftMenu);
} else {
mDrawerLayout.openDrawer(mDrawerLeftMenu);
}
}
5、关闭手势滑动
public void closeDrawerGestureSlide() {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
}
6、打开手势滑动
public void openDrawerGestureSlide() {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}