Bundle is a useful data holder, which maps String values to various
Parcelable types. So basically it is a heterogenous key/value map. Bundles are used in
Intents, Activities and Fragments for transporting data. I would like to describe how I work with Bundles on Android and show you some good tips.

Activity

When you are creating a new instance of Activity via Intent, you can pass some extra data to the Activity. Data are stored in Bundle and can be retrieved by calling
getIntent().getExtras(). It's a good practise to implement static method
newIntent() which returns a new Intent that can be used to start the Activity. This way you have compile time checking for the arguments passed to the Activity. This pattern is suitable for Service and Broadcast as well.

Bundle is also used if the Activity is being re-initialized (e.g. because of configuration changes) for keeping the current state of the instance. You can supply some data in
onSaveInstanceState(Bundle) and retrieve them back in onCreate(Bundle) method or
onRestoreInstanceState(Bundle). Main difference between these methods is that
onRestoreInstanceState(Bundle) is called after onStart(). Sometimes it's convenient to restore data here after all of the initialization has been done. Another purpose could be allowing subclasses to decide whether to use your default
implementation.

See example code below. Note that EXTRA_PRODUCT_ID constant is public. That's because we could need it in a Fragment encapsulated in this Activity.

public class ExampleActivity extends Activity
{
public static final String EXTRA_PRODUCT_ID = "product_id";
public static final String EXTRA_PRODUCT_TITLE = "product_title"; private static final String SAVED_PAGER_POSITION = "pager_position"; public static Intent newIntent(Context context, String productId, String productTitle)
{
Intent intent = new Intent(context, ExampleActivity.class); // extras
intent.putExtra(EXTRA_PRODUCT_ID, productId);
intent.putExtra(EXTRA_PRODUCT_TITLE, productTitle); return intent;
} @Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_example); // restore saved state
if(savedInstanceState != null)
{
handleSavedInstanceState(savedInstanceState);
} // handle intent extras
Bundle extras = getIntent().getExtras();
if(extras != null)
{
handleExtras(extras);
}
} @Override
public void onSaveInstanceState(Bundle outState)
{
// save current instance state
super.onSaveInstanceState(outState); // TODO
} @Override
public void onRestoreInstanceState(Bundle savedInstanceState)
{
// restore saved state
super.onRestoreInstanceState(savedInstanceState); if(savedInstanceState != null)
{
// TODO
}
} private void handleSavedInstanceState(Bundle savedInstanceState)
{
// TODO
} private void handleExtras(Bundle extras)
{
// TODO
}
}

Fragment

When you are creating a new instance of Fragment, you can pass arguments through
setArguments(Bundle) method. Data can be retrieved with getArguments() method. It would be a mistake to supply initialization data through an overloaded constructor. Fragment instance can be re-created (e.g. because of configuration
changes) so you would lose data, because constructor with extra parameters is not called when re-initializing Fragment. Only empty constructor is called. Best way to solve this problem is implementing static creator method
newInstance() which returns a new instance of Fragment and sets the arguments via
setArguments(Bundle).

Fragment state can be saved using onSaveInstanceState(Bundle) method. It is similar to the Activity. Data can be restored in
onCreate(Bundle), onCreateView(LayoutInflater, ViewGroup, Bundle),
onActivityCreated(Bundle) or onViewStateRestored(Bundle) methods.

Fragment has also access to the Intent extras which were passed during creating the Activity instance. You can get this extra data by calling
getActivity().getIntent().getExtras().

See example code below.

public class ExampleFragment extends Fragment
{
private static final String ARGUMENT_PRODUCT_ID = "product_id"; private static final String SAVED_LIST_POSITION = "list_position"; public static ExampleFragment newInstance(String productId)
{
ExampleFragment fragment = new ExampleFragment(); // arguments
Bundle arguments = new Bundle();
arguments.putString(ARGUMENT_PRODUCT_ID, productId);
fragment.setArguments(arguments); return fragment;
} public ExampleFragment() {} @Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState); // handle fragment arguments
Bundle arguments = getArguments();
if(arguments != null)
{
handleArguments(arguments);
} // restore saved state
if(savedInstanceState != null)
{
handleSavedInstanceState(savedInstanceState);
} // handle intent extras
Bundle extras = getActivity().getIntent().getExtras();
if(extras != null)
{
handleExtras(extras);
}
} @Override
public void onSaveInstanceState(Bundle outState)
{
// save current instance state
super.onSaveInstanceState(outState); // TODO
} private void handleArguments(Bundle arguments)
{
// TODO
} private void handleSavedInstanceState(Bundle savedInstanceState)
{
// TODO
} private void handleExtras(Bundle extras)
{
// TODO
}
}

You can find example code also on my GitHub in Android Templates and Utilities repo. This blogpost was inspired by Nick Butcher's post on Google Plus. Gotta some questions or ideas about Bundles? Follow me on
Twitter or Google Plus.

Handling bundles in activities and fragments的更多相关文章

  1. Android Handling back press when using fragments in Android

    In MainActivity: getSupportFragmentManager().beginTransaction().replace(R.id.gif_contents, gifPageTw ...

  2. Android -- Handling back button press Inside Fragments

    干货(1) 首先创建一个抽象类BackHandledFragment,该类有一个抽象方法onBackPressed(),所有BackHandledFragment的子类在onBackPressed方法 ...

  3. Android AppBar

    AppBar官方文档摘记 2016-6-12 本文摘自Android官方文档,为方便自己及其他开发者朋友阅读. 章节目录为"Develop > Training > Best P ...

  4. 【转载】安卓APP架构

    注:本篇博文转载于 http://my.oschina.net/mengshuai/blog/541314?fromerr=z8tDxWUH 本文介绍了文章作者从事了几年android应用的开发,经历 ...

  5. EventBus学习入门

    EventBus Features What makes greenrobot's EventBus unique, are its features: Simple yet powerful: Ev ...

  6. ActionBar官方教程(7)自定义操作项的view,如何得到它及处理它的事件

    Adding an Action View An action view is a widget that appears in the action bar as a substitute for ...

  7. Android API 指南

    原文链接:http://android.eoe.cn/topic/android_sdk Android API 指南 - Android API Guides 应用的组成部分 - Applicati ...

  8. Android设计和开发系列第二篇:Action Bar(Develop—API Guides)

    Action Bar IN THIS DOCUMENT Adding the Action Bar Removing the action bar Using a logo instead of an ...

  9. Creating a Fragment: constructor vs newInstance()

    from stack overflow and another chapter I recently grew tired of constantly having to know String ke ...

随机推荐

  1. NodeJs学习记录(一)初步学习,杂乱备忘

    2016/12/26 星期一 1.在win7下安装了NodeJs 1)进入官网 https://nodejs.org/en/download/,下载对应的安装包,我目前下载的是node-v6.2.0- ...

  2. Python,报错NameError: name 'math' is not defined

    1 #-*- coding : utf-8 -*- 2 import math 3 4 def move(x, y, step, angle=0): 5 nx = x + step * math.co ...

  3. css边框样式、边框配色、边框阴影、边框圆角、图片边框

     边框样式 点线式边框 破折线式边框 直线式边框 双线式边框 槽线式边框 脊线式边框 内嵌效果的边框 突起效果的边框 <div style="width: 300px; height: ...

  4. android调用webservice接口获取信息

    我的有一篇博客上讲了如何基于CXF搭建webservice,service层的接口会被部署到tomcat上,这一篇我就讲一下如何在安卓中调用这些接口传递参数. 1.在lib中放入ksoap2的jar包 ...

  5. DatePickerDialog日期对话框以及回调函数的用法

    DatePickerDialog类的实例化需要用到回调接口,如下定义: android.app.DatePickerDialog.DatePickerDialog(Context context, O ...

  6. IDEA打可执行jar包

    流程: 1. File ->Project Structure -> Artifacts -> + -> JAR -> From modules with depende ...

  7. [C#源码]自动更改桌面背景

    操作代码:ChangeDesktop.cs using System;using System.Collections.Generic;using System.ComponentModel;usin ...

  8. Spring Boot 缓存的基本用法

    目录 一.目的 二.JSR-107 缓存规范 三.Spring 缓存抽象 四.Demo 1.使用 IDEA 创建 Spring Boot 项目 2.创建相应的数据表 3.创建 Java Bean 封装 ...

  9. mac os 10.10解决pod问题

    转一下 http://leancodingnow.com/how-to-get-cocoapods-work-on-yosemite/

  10. 原来 JS 是这样的 - 关于 this

    引子 习惯了别的语言的思维习惯而不专门了解 JavaScript 的语言特性的话,难免踩到一些坑. 上一篇文章 中简单总结了关于 提升, 严格模式, 作用域 和 闭包 的几个常见问题,当然这仅仅是了解 ...