OSChina中使用DrawerLayout完成侧滑菜单功能。尝试学着写了一个DrawerLayout Demo
效果图
Demo地址
实现过程
1.编写DrawerLayout的布局文件drawerlayout_custom.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/dl_left"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="DrawerLayoutDemo" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#fff">
<ListView
android:id="@+id/lv_left_menu"
android:layout_width="match_parent"
android:layout_height="match_parent"></ListView>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
2.在activity_main中include该布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:background="#c0c0c0"
android:id="@+id/tb_custom"
android:layout_width="match_parent"
android:layout_height="wrap_content"></android.support.v7.widget.Toolbar>
<include layout="@layout/drawerlayout_custom" />
</LinearLayout>
3.为显示Toolbar,需修改styles.xml中的属性为NoActionBar:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
</style>
</resources>
4.MainActivity的OnCreate中添加关键代码实现侧滑效果
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//创建返回键,并实现打开关/闭监听
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.open, R.string.close) {
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
mDrawerToggle.syncState();
mDrawerLayout.setDrawerListener(mDrawerToggle);
//设置菜单列表
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, lvs);
lvLeftMenu.setAdapter(arrayAdapter);
参考链接:
[Material Design]使用Toolbar + DrawerLayout快速实现高大上菜单侧滑
android中ActionBar中setDisplayHomeAsUpEnabled和setHomeButtonEnabled和setDisplayShowHomeEnabled方法的理解