laylout文件:
<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">
<!-- The main content view -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<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="1dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:textColor="#fff"
android:background="?android:attr/activatedBackgroundIndicator"
android:minHeight="?android:attr/listPreferredItemHeightSmall"/>
package com.example.navigationdemo;

import android.os.Bundle;
import android.app.Activity;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView; public class MainActivity extends Activity {
private String[] mPlanetTiles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlanetTiles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout= (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList= (ListView) findViewById(R.id.left_drawer);
mDrawerList.setAdapter(new ArrayAdapter<String>(this,R.layout.drawer_list_item,mPlanetTiles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class DrawerItemClickListener implements ListView.OnItemClickListener{ @Override
public void onItemClick(AdapterView parent, View view, int position,
long id) {
// TODO Auto-generated method stub
selectItem(position);
} }
public void selectItem(int position) {
// TODO Auto-generated method stub
Log.d("",position+"");
}
}

到了这一步就基本可用跑起来了,运行看看效果:

点两下:

不过还有点问题,左边的侧滑栏并不会在点击后自动收回。我们继续。

继续增加下面的代码:

public void selectItem(int position) {
// Create a new fragment and specify the planet to show based on position
Log.d("",position+"");
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()//此函数返回一个FragmentTransactiond对象,用来开始一系列对Fragments的操作
.replace(R.id.content_frame, fragment)//Replace an existing fragment that was added to a container
//依旧返回返回一个FragmentTransactiond对象
.commit();
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
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);
          //作用类似于findViewById()。不同点是LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化
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;
}

同样,增加一个fragment_planet的布局:

<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:gravity="center"
android:padding="32dp" />

当你点击了listview中的项目时,系统就会setOnItemClickListener()函数设定的OnItemClickListener 类里的onItemClick()函数。

上面这段代码的作用就是在点击了Drawer对应项目之后,新生成一个Fragment,将现有的替换掉。然后关闭Drawer。

官方demo中用的是几颗行星的图片,所以对应变量也是,我随便放了几张图片上去:

不过还是有点小问题,程序刚运行的时候,并没有任何fragment被载入,程序是一片空白。

接下来要实现的效果是点击actionbar上的图标来展示drawer,同时还有一个指示的动画。

我们需要使用ActionBarDrawerToggle的类:

This class provides a handy way to tie together the functionality of DrawerLayout and the framework ActionBar to implement the recommended design for navigation drawers.

To use ActionBarDrawerToggle, create one in your Activity and call through to the following methods corresponding to your Activity callbacks:

Call syncState() from your Activity's onPostCreate to synchronize the indicator with the state of the linked DrawerLayout after onRestoreInstanceState has occurred.

ActionBarDrawerToggle can be used directly as a DrawerLayout.DrawerListener, or if you are already providing your own listener, call through to each of the listener methods from your own.

在activity的OnCreate函数里加入:

getActionBar().setDisplayHomeAsUpEnabled(true);  显示向上箭头 
getActionBar().setHomeButtonEnabled(true);让程序图标可以点击。

接下来在,activity里重写一个函数,用来在点击图标后drawer。

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items... return super.onOptionsItemSelected(item);
}

其余的应该都是保持、恢复程序状态的函数。

ActionBarDrawerToggle也提供了onDrawerClosed(View drawerView) onDrawerOpened(View drawerView) 的函数,动态改变actionbar的标题就是用这个。比较有技巧的一点是,每次改变标题的时候需要把之前的标题保存下来。

项目代码参考:http://developer.android.com/training/implementing-navigation/nav-drawer.html

Android 学习笔记:Navigation Drawer的更多相关文章

  1. 【转】Pro Android学习笔记(四):了解Android资源(下)

    处理任意的XML文件 自定义的xml文件放置在res/xml/下,可以通过R.xml.file_name来获取一个XMLResourceParser对象.下面是xml文件的例子: <rootna ...

  2. Android 学习笔记之Volley(七)实现Json数据加载和解析...

    学习内容: 1.使用Volley实现异步加载Json数据...   Volley的第二大请求就是通过发送请求异步实现Json数据信息的加载,加载Json数据有两种方式,一种是通过获取Json对象,然后 ...

  3. Android学习笔记进阶之在图片上涂鸦(能清屏)

    Android学习笔记进阶之在图片上涂鸦(能清屏) 2013-11-19 10:52 117人阅读 评论(0) 收藏 举报 HandWritingActivity.java package xiaos ...

  4. android学习笔记36——使用原始XML文件

    XML文件 android中使用XML文件,需要开发者手动创建res/xml文件夹. 实例如下: book.xml==> <?xml version="1.0" enc ...

  5. Android学习笔记之JSON数据解析

    转载:Android学习笔记44:JSON数据解析 JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,采用完全独立于语言的文本格式,为Web应用开发提供了一种 ...

  6. udacity android 学习笔记: lesson 4 part b

    udacity android 学习笔记: lesson 4 part b 作者:干货店打杂的 /titer1 /Archimedes 出处:https://code.csdn.net/titer1 ...

  7. Android学习笔记36:使用SQLite方式存储数据

    在Android中一共提供了5种数据存储方式,分别为: (1)Files:通过FileInputStream和FileOutputStream对文件进行操作.具体使用方法可以参阅博文<Andro ...

  8. Android学习笔记之Activity详解

    1 理解Activity Activity就是一个包含应用程序界面的窗口,是Android四大组件之一.一个应用程序可以包含零个或多个Activity.一个Activity的生命周期是指从屏幕上显示那 ...

  9. Pro Android学习笔记 ActionBar(1):Home图标区

     Pro Android学习笔记(四八):ActionBar(1):Home图标区 2013年03月10日 ⁄ 综合 ⁄ 共 3256字 ⁄ 字号 小 中 大 ⁄ 评论关闭 ActionBar在A ...

  10. 【转】Pro Android学习笔记(九八):BroadcastReceiver(2):接收器触发通知

    文章转载只能用于非商业性质,且不能带有虚拟货币.积分.注册等附加条件.转载须注明出处:http://blog.sina.com.cn/flowingflying或作者@恺风Wei-傻瓜与非傻瓜 广播接 ...

随机推荐

  1. web程序定时器

    package com.timer; import java.util.Calendar; import java.util.Date; import java.util.Timer; import ...

  2. 使用C++实现学生管理系统

    我在前面的博客中分别使用C语言的动态数组和链表实现了学生成绩管理系统.近期正好在学习C++,于是我便使用C++实现了学生成绩管理系统.算法和前面的C语言的动态数组实现的学生成绩管理系统几乎相同,仅仅是 ...

  3. sql server执行动态拼接sql(带传参数)和去掉小数点后0的函数

    1 exec sp_executesql N'SELECT 2 [Extent2].[Id] AS [Id], 3 [Extent2].[Name] AS [Name], 4 [Extent2].[D ...

  4. Google Maps API 将开始收费

    Google Maps API 将开始收费 一.总结 一句话总结:国外的话openstreetmap或许不错 国内的话就高德吧 二.Google Maps API 将开始收费 曾经免费的 Google ...

  5. Array数组的排序与二分查字法

    import java.util.Arrays; public class sort { public static void main(String[] args) { // TODO 自动生成的方 ...

  6. rem 、em

    介绍:rem是相对字体单位:根据html根元素大小而定,同样可作为宽高等单位: 适配原理:将px替换成rem,采用rem适配移动web的原理,根据不同屏幕宽度设置html的font-size的大小: ...

  7. BZOJ 2793: [Poi2012]Vouchers(调和级数)

    Time Limit: 20 Sec  Memory Limit: 64 MBSubmit: 582  Solved: 250[Submit][Status][Discuss] Description ...

  8. centos下nginx配置

    转自  http://www.linuxidc.com/Linux/2016-09/134907.htm 安装所需环境 Nginx 是 C语言 开发,建议在 Linux 上运行,当然,也可以安装 Wi ...

  9. ActiveMQ学习笔记(6)----ActiveMQ整合Spring开发

    1. 添加依赖 spring 提供了对JMS的支持,需要添加Spring支持jms的包和Spring的核心包,如下: <dependency> <groupId>org.apa ...

  10. sass的用法小结(三)

    5. 混合器; 如果你的整个网站中有几处小小的样式类似(例如一致的颜色和字体),那么使用变量来统一处理这种情况是非常不错的选择.但是当你的样式变得越来越复杂,你需要大段大段的重用样式的代码,独立的变量 ...