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. 110个经常使用Oracle函数总结

    1. ASCII 返回与指定的字符相应的十进制数; SQL> select ascii(A) A,ascii(a) a,ascii(0) zero,ascii( ) space from dua ...

  2. Oracle分析函数ntile

    有这么一个需求.将课程的成绩分成四个等级,为学生打A.B.C.D的绩效. drop table course purge; create table course (   id number,   g ...

  3. m_Orchestrate learning system---二十、如何写代码不容易犯错

    m_Orchestrate learning system---二十.如何写代码不容易犯错 一.总结 一句话总结:能排序多排序 这次查错的启示: 1.代码数据更规整:要是取出的数据排序的话可以减少很多 ...

  4. ORACLE 11GR2 RAC的网络规划解析

    在ORACLE 11gR2中,安装RAC发生了显著变化.在10g以及11gR1的时代,安装RAC的步骤是先安装CRS,再安装DB,而到了11gR2的时代,crs与asm被集成在一起,合称为GRID,必 ...

  5. 关于如何让cell一直保持选中?

    在M上 1.cell的展示,一直都是依靠数据源的支持.所以,必须要在数据源里面新增bool,默认为false 在V上 2.cell的setModel方法里面,将数据源的新增bool赋值为cell的是否 ...

  6. Servlet简单计算器 2.0

    jsp 输入界面: <%@ page language="java" contentType="text/html; charset=UTF-8" pag ...

  7. POJ 1979 Red and Black (简单dfs)

    题目: 简单dfs,没什么好说的 代码: #include <iostream> using namespace std; typedef long long ll; #define IN ...

  8. JavaScript学习——JS事件总结

    回顾之前已经使用过的事件 (onsubmit.onclick.onload.onfocus.onblur.onmouseover.onmouseout) onfocus/onblur:聚焦离焦事件,用 ...

  9. Java中如何解决线程安全问题

    给出一个问题,如下: 解决方案如下: public class Demo_5 { public static void main(String[] args) { //创建一个窗口 TicketWin ...

  10. 修改input标签中的placeholder样式

    input::-webkit-input-placeholder { color: #fff !important; } input:-moz-placeholder { color: #fff !i ...