首先,要将Activity的根布局改为android.support.v4.widget.DrawerLayout 

其次,要为侧滑栏的布局控件设置属性android:layout_gravity="start"(左边)或android:layout_gravity="end"(右边)。

布局文件如下:

< android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"

  android:id="@+id/drawerLayout"

  android:layout_width="match_parent"

  android:layout_height="match_parent"

  android:background="@color/lightgray"

  android:orientation="vertical" >

  < !-- 主菜单 -- >

  < LinearLayout

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:background="@color/white"

    android:orientation="vertical" >

  < /LinearLayout>

  < !--侧滑栏-- >

  < ListView

    android:id="@+id/lvLeftDrawer"

    android:layout_width="150dp"

    android:layout_height="wrap_content"

    android:paddingTop="10dp"

    android:layout_gravity="start"

    android:background="@color/white"

   android:gravity="left|center"

    android:choiceMode="singleChoice"

    android:divider="@android:color/transparent"

    android:dividerHeight="1dp" / >

< /android.support.v4.widget.DrawerLayout>

在Activity后台代码中需要对DrawerLayout进行初始化:

private void initDrawerLayout() {

drawerLayout = (DrawerLayout) super.findViewById(R.id.drawerLayout);

// drawerLayout.setScrimColor(Color.TRANSPARENT);// 侧滑时主界面的变化颜色

drawerLayout.setScrimColor(Color.parseColor("#880bb9f6"));

toggle = new ActionBarDrawerToggle(this,

drawerLayout,// 设置左右滑动打开关闭侧滑栏的动作

R.drawable.ic_launcher, R.string.drawer_open,

R.string.drawer_close) {

public void onDrawerClosed(View drawerView) {// 控制侧边栏的关闭

super.onDrawerClosed(drawerView);

}

public void onDrawerOpened(View drawerView) {// 控制侧边栏打开

super.onDrawerOpened(drawerView);

}

};

drawerLayout.setDrawerListener(toggle);

}

通过点击某个控件来控制侧滑栏的显示和隐藏:

@Override

public void onClick(View v) {

switch (v.getId()) {

case R.id.tvTitle:// 打开侧边栏

toggleLeftSliding();

break;

default:

break;

}

}

private void toggleLeftSliding() {// 该方法控制侧滑栏的显示和隐藏

if (drawerLayout.isDrawerOpen(Gravity.START)) {

drawerLayout.closeDrawer(Gravity.START);

} else {

drawerLayout.openDrawer(Gravity.START);

}

}

更多相关文章

  1. 强烈推荐:Android完全自学从零开始
  2. android界面设计(一)侧边栏的两种实现方式
  3. TextView设置中文粗体
  4. Android(安卓)Studio 实现九宫格
  5. Android(安卓)invalidate
  6. Android(安卓)之 Fragment的动态加载
  7. Android调色板---palette
  8. Listview中的button点击事件
  9. Android控件笔记——使用RadioGroup和RadioButton实现单选效果

随机推荐

  1. Android O新特性系列
  2. xmlns:android和xmlns:mi
  3. android实现通知栏下载更新app示例
  4. Android实现语音识别代码
  5. Android中 获取手机通讯录和手机机主手机
  6. [连载 4/15] Android 从入门到精通Exampl
  7. 疯狂android讲义---intent-filter
  8. Android踩坑日记:自定义水平和圆形Progres
  9. 【极客之作】快到极致的Android模拟器—
  10. Android中Recyclerview或ListView列表条