- main.xml编辑
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
<!--指定一个命名空间-->
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawerlayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout <!--主布局,在此布局下即是Activity显示内容-->
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--定义一个Toolbar控件 -->
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"/>
</RelativeLayout>
<!--左菜单布局,这里用的是NavigationView控件,也可以用LinearLayout布局-->
<!--android:layout_gravity="left"(左菜单)
android:layout_gravity="rigth"(右菜单)属性判断是左菜单还是右菜单-->
<android.support.design.widget.NavigationView
android:id="@+id/view"
android:layout_width="250dp"
android:layout_height="match_parent"
android:layout_gravity="left"
app:menu="@menu/menu"
app:headerLayout="@layout/header"/>
</android.support.v4.widget.DrawerLayout>
在使用app:时需要使用xmlns:app="http://schemas.android.com/apk/res-auto"
定义一个命名空间
- 编辑MainActivity.java
//划重点!!要继承ActionBarActivity类
public class MainActivity extends ActionBarActivity
{
private Toolbar toolbar;
private DrawerLayout drawer;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//绑定id
toolbar=(Toolbar) findViewById(R.id.toolbar);
drawer=(DrawerLayout) findViewById(R.id.drawerlayout);
//替换系统状态栏
setSupportActionBar(toolbar);
/*旋转特效按钮ActionBarDrawerToggler
*这里需要5个参数
*1.this Activity
*2.DrawerLayout
*3.Toolbar
*4,5 开启和关闭的资源文件
*需要进行定义,在res/values/string.xml文件进行定义
*/
ActionBarDrawerToggle toggle=new ActionBarDrawerToggle(this,drawer,toolbar,R.string.open,R.string.close){};
//显示一个菜单按钮
toggle.syncState();
//绑定监听器
drawer.setDrawerListener(toggle);
}
}
- 编辑string.xml文件
<string name="open">开启</string>
<string name="close">关闭</string>