目录:android.support.v4.widget.DrawerLayout
布局xml中:
<?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"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<!--主界面-->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#00ffffff" />
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="我是主界面内容" />
</RelativeLayout>
<!-- 导航菜单 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="left"
android:background="#ffffff">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="我是侧滑菜单内容" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
res string资源:
<string name="navigation_drawer_open">Open navigation drawer</string>
<string name="navigation_drawer_close">Close navigation drawer</string>
代码中:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//执行这行代码,菜单栏的标题会显示
//setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
//推荐使用,设置菜单滑动监听(原来的drawer.setDrawerListener废弃)
drawer.addDrawerListener(new DrawerLayout.DrawerListener() {
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
}
@Override
public void onDrawerOpened(View drawerView) {
}
@Override
public void onDrawerClosed(View drawerView) {
}
@Override
public void onDrawerStateChanged(int newState) {
}
});
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
补充:
1、必须指定侧滑菜单布局的android:layout_gravity属性,从左向右滑出菜单:android:layout_gravity = "start";从右向左滑出菜单:android:layout_gravity = "end"时,不建议使用left和right!(该属性定义菜单的位置,主布局不用写该属性)
2、侧滑菜单的宽度可以直接设置,以dp为单位,不建议超过320dp,通常设置为240dp
3、常用设置
打开侧拉菜单:
mDrawerLayout.openDrawer(Gravity.LEFT);
关闭侧拉菜单:
mDrawerLayout.closeDrawer(menu_layout);
菜单是否开启,开启返回true,关闭返回false:
mDrawerLayout.isDrawerOpen(menu_layout);