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. hdu 4628 Pieces(状态压缩+记忆化搜索)

    Pieces Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others) Total S ...

  2. hdoj 4548 美素数 【打表】

    另类打表:将从1到n的满足美素数条件的数目赋值给prime[n],这样最后仅仅须要用prime[L]减去prime[R-1]就可以: 美素数 Time Limit: 3000/1000 MS (Jav ...

  3. Android sdCard路径问题

    一,获取Android设备的全部存储设备,这里边肯定有一个能用的 StorageManager sm = (StorageManager) context.getSystemService(Conte ...

  4. vue Render scopedSlots

    render 中 slot 的一般默认使用方式如下: this.$slots.default 对用 template的<slot>的使用没有name . 想使用多个slot 的话.需要对s ...

  5. 获取json数据后在 地图上打点,根据 json不断移动点的位置

    <?php echo <<<_END <!doctype html> <html> <head> <meta charset=&quo ...

  6. awesome python 中文版 相见恨晚!(pythonNB的第三方资源库)

    Awesome Python中文版来啦! 原文链接:Python 资源大全 内容包括:Web框架.网络爬虫.网络内容提取.模板引擎.数据库.数据可视化.图片处理.文本处理.自然语言处理.机器学习.日志 ...

  7. 用ksh运行一个helloworld

    本文目的在于记录和回顾.不建议当教程. Linux上没有ksh的话yum install ksh就可以了 直接上图 vim一个文件后缀名是ksh 内容是和shell差不多 然后赋予这个文件可执行权限 ...

  8. JqGrid 查询时未设置初始页码导致的问题

    本文所述问题发生在查询的数据有至少2页数据时的情况下.本例中的产品质量查询就是这样. 第一步:查询该时间段内的数据,结果为13页的数据内容,显示当前页第1页.如下图所示: 第二步:点击翻页按钮,打开第 ...

  9. solarwind之安装

      1.  安装组件   2.  安装组件sql   3.  安装   4.  接受协议   5.  安装路径   6.  安装状态   7.  继续   8.  激活     9.  完成安装

  10. FCC高级编程之Inventory Update

    Inventory Update Compare and update the inventory stored in a 2D array against a second 2D array of ...