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. CF817C Really Big Numbers

    思路: 二分. 实现: #include <iostream> #include <cstdio> using namespace std; typedef long long ...

  2. TensorFlow OOM when allocating tensor with shape[5000,384707]

    在session范围内不要进行eval()或者convert_to_tensor()操作, 否则会造成OOM,或者报出错误:GraphDef cannot be larger than 2GB usi ...

  3. QQ应用前景与范围文档

    QQ软件 前景与范围文档       当前版本: 版本1 作   者: 李飞 完成日期: 2013年11月3日 1.  业务需求 1.1 应用背景 20世纪后期网络的应用和21世纪的飞速发展,网络已经 ...

  4. 导入RPA应该了解的一些知识

    上次概要介绍了下RPA的基本知识,这次说一下导入RPA时应该知道的一些知识点. RPA是为了实现用软件自动化代替在各个行业中用人操作电脑办公的这部分业务,即使是在多个应用之间需要共享数据才能完成的业务 ...

  5. handlesocket.md

    [介绍](http://www.uml.org.cn/sjjm/201211093.asp ) * 查看启动参数     `service mariadb status > st.txt`   ...

  6. 05Servlet example

    dgdfgdfggggggg Servlet 表单数据 在客户端,GET通过URL提交数据,数据在URL中可见:POST把数据放在form的数据体内提交.GET提交的数据最多只有1024字节:POST ...

  7. C++ 11常见功能介绍:auto,decltype,nullptr,for,lambda

    什么是C++11 C++11是曾经被叫做C++0x,是对目前C++语言的扩展和修正,C++11不仅包含核心语言的新机能,而且扩展了C++的标准程序库(STL),并入了大部分的C++ Technical ...

  8. scp 上传文件自动录入密码

    --- 服务器IP地址 des_host=serverIp 服务器存储路径(文件上传后存储指定目录下) des_direc=/home/lk/ 服务器用户密码 des_pass=root_passwo ...

  9. 打造完美的ImageLoader——LruCache+DiskLruCache

    做android应用少不了要和网络打交道,在我刚开始学android的时候总是处理不好网络图片的加载,尤其是图片乱跳的问题,后来发现了各种缓存图片的方法:本地缓存.软引用.LruCache.... 我 ...

  10. 题解 洛谷P3203/BZOJ2002【[HNOI2010]弹飞绵羊】

    裸的LCT,关键是要怎么连边,怎么将这种弹飞关系转化成连边就行了. 那么我们可以这样连边: 一个节点i的爸爸就是i+ki. 没有i+ki那么就被弹飞了,即\(i\)的爸爸是虚拟节点n+1. 那么怎么求 ...