实现效果
实现代码
1.新建项目
2.activity_main.xml
<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">
t in both dimensions. -->
<RelativeLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="这是主界面"/>
</RelativeLayout>>
<RelativeLayout
android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
android:background="#111">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="这是侧边栏"/>
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
3.MainActivity
public class MainActivity extends ActionBarActivity {
private ActionBarDrawerToggle toggle; //这个用v4包
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
initActionBar();
}
private void initActionBar() {
ActionBar actionBar = getSupportActionBar(); // 获取到一个可以向下兼容的ActionBar对象
actionBar.setDisplayHomeAsUpEnabled(true); // 设置ActionBar的Home图标显示一个向上的按钮,并且可以点击
// 查找到抽屉布局对象
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// 抽屉布局的控制开关,最后两个参数一般用不上,可以写0,用于指定打开和关闭抽屉的描述
toggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer_am, -1, -1);
toggle.syncState(); // 同步菜单和AcionBar的状态,把ActionBarDrawerToggle构造方法中的图片显示出来
drawerLayout.setDrawerListener(toggle); // 设置抽屉的监听器,用于监听抽屉的打开、关闭、滑动等等
}
/**当ActionBar上的选项菜单被点击的时候会执行这个方法**/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (toggle.onOptionsItemSelected(item)) {
return true; // 如果抽屉开关返回了true则说明需要消费掉这个事件。
}
return super.onOptionsItemSelected(item);
}
}