一.概述

目前侧滑框架已经很多了,但是我常用的也就那么2个 ,slidingmenu 和sidemenu-android, 但是项目要求使用官方的,所以就看了一下drawerlayout

二.代码

官方代码还是很好理解的,之前也用过,但是真实项目没使用过 ,代码如下

package com.kun.drawer_layout;

import java.util.Locale;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast; public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle; private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); mTitle = mDrawerTitle = getTitle();
//侧边栏 item 名称
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
//侧边栏容器对象
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//侧边栏 Listview
mDrawerList = (ListView) findViewById(R.id.left_drawer); //设置侧滑阴影,
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
//设置侧滑 adapter ,并添加点击事件
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); //设置左上角 actionbar 图标可见
getActionBar().setDisplayHomeAsUpEnabled(true);
//需要api level 14 使用home-icon 可点击
getActionBar().setHomeButtonEnabled(true); //actionbar 抽屉开关
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
//侧滑关闭
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);//设置侧滑item名字到 actionbar上面
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
//侧滑打开
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle); if (savedInstanceState == null) {
selectItem(0);
}
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
} /* Called whenever we call invalidateOptionsMenu() */
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
} @Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch(item.getItemId()) {
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
} /* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
} //显示侧滑item --内容区域
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args); FragmentManager fragmentManager = getFragmentManager();
//让fragment替换 帧布局内容
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit(); //更新选中的 item ,并关闭抽屉
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} @Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
} /**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/ @Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
} @Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
} /**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class PlanetFragment extends Fragment {
public static final String ARG_PLANET_NUMBER = "planet_number"; public PlanetFragment() {
// Empty constructor required for fragment subclasses
} @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = getResources().getStringArray(R.array.planets_array)[i]; int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
}
}

用到的几个布局如下

<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<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"> <!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" /> <!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
The drawer is given a fixed width in dp and extends the full height of
the container. A solid background is used for contrast
with the content view. -->
<ListView
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"/> <!--
android:choiceMode 选中状态 跟itemclick没有冲突
none 值为0,表示无选择模式;
singleChoice 值为1,表示最多可以有一项被选中;
multipleChoice 值为2,表示可以多项被选中。 android:layout_gravity left或right left或start right或end
表示在抽屉里的效果是从左到右还是从右到左出现
-->
</android.support.v4.widget.DrawerLayout>

侧滑列表很简单,就是一个Listview装载了 TextView , 侧滑item对应的是fragment, 而fragment 布局更简单只是 一个图片

最后来张图

最新文章

  1. 防御病毒邮件得看U-Mail邮件网关
  2. 如何保存联系人到系统通讯录(android)
  3. Java 自动装箱与拆箱
  4. MySQl的几个配置项
  5. JavaScript 运行机制详解:再谈Event Loop
  6. redhat 新装后不能联网
  7. [Objective-c 基础 - 3.2] ARC
  8. (转) Eclipse - Python - Installation of PyDev with a Python Hello World tutorial
  9. Jersey的RESTful简单案例demo
  10. Python高手之路【九】python基础之迭代器与生成器
  11. angular $stateProvider 路由的使用
  12. ubuntu下无法编译ruby-2.1.5提示something wrong with CFLAGS -arch x86_64
  13. UML教程
  14. 如何在基于Bytom开发过程中使用Bigchaindb
  15. python模块--re模块
  16. Linux Kafka源码环境搭建
  17. 9.1C#中类的定义
  18. mysql 统计 group by 之后的 group 的个数
  19. bzoj3862
  20. [Objective-C语言教程]结构体(17)

热门文章

  1. azure k8s netcore 程序初次部署
  2. 网络编程网络协议篇(osi七层协议)
  3. django报错信息解决方法
  4. Oracle delete和truncate实践操作之一
  5. 迁移学习(Transformer),面试看这些就够了!(附代码)
  6. java 程序执行顺序之继承
  7. Scala 系列(十)—— 函数 &amp; 闭包 &amp; 柯里化
  8. 从零开始搭建Java开发环境第二篇:如何在windows10里安装MySQL
  9. JavaScript 防抖
  10. Delphi - Indy TIdFTP控件实现文件的上传和下载