Handling bundles in activities and fragments
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的更多相关文章
- Android Handling back press when using fragments in Android
In MainActivity: getSupportFragmentManager().beginTransaction().replace(R.id.gif_contents, gifPageTw ...
- Android -- Handling back button press Inside Fragments
干货(1) 首先创建一个抽象类BackHandledFragment,该类有一个抽象方法onBackPressed(),所有BackHandledFragment的子类在onBackPressed方法 ...
- Android AppBar
AppBar官方文档摘记 2016-6-12 本文摘自Android官方文档,为方便自己及其他开发者朋友阅读. 章节目录为"Develop > Training > Best P ...
- 【转载】安卓APP架构
注:本篇博文转载于 http://my.oschina.net/mengshuai/blog/541314?fromerr=z8tDxWUH 本文介绍了文章作者从事了几年android应用的开发,经历 ...
- EventBus学习入门
EventBus Features What makes greenrobot's EventBus unique, are its features: Simple yet powerful: Ev ...
- ActionBar官方教程(7)自定义操作项的view,如何得到它及处理它的事件
Adding an Action View An action view is a widget that appears in the action bar as a substitute for ...
- Android API 指南
原文链接:http://android.eoe.cn/topic/android_sdk Android API 指南 - Android API Guides 应用的组成部分 - Applicati ...
- 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 ...
- Creating a Fragment: constructor vs newInstance()
from stack overflow and another chapter I recently grew tired of constantly having to know String ke ...
随机推荐
- 2199. [HZOI 2016] 活动投票
★★ 输入文件:hztp.in 输出文件:hztp.out 简单对比 时间限制:0.5 s 内存限制:2 MB [题目描述] 衡中活动很多,人也很多,一次活动有n个学生参与投票,现已知 ...
- ubuntu下删除和新建用户(并有su权限)
http://blog.csdn.net/speedme/article/details/8206144ubuntu下删除和新建用户(并有su权限) 如何创建ubuntu新用户?输入:sudo add ...
- C++ 泛型程序设计与STL模板库(1)---泛型程序设计简介及STL简介与结构
泛型程序设计的基本概念 编写不依赖于具体数据类型的程序 将算法从特定的数据结构中抽象出来,成为通用的 C++的模板为泛型程序设计奠定了关键的基础 术语:概念 用来界定具备一定功能的数据类型.例如: 将 ...
- day14-二分法、匿名函数、内置函数以及面向过程编程
目录 二分法 匿名函数 内置函数 面向过程编程 二分法 二分法查找适用于数据量较大时,但是数据需要先排好顺序.主要思想是:(设查找的数组区间为array[low, high]) (1)确定该区间的中间 ...
- 02网页<body></body>常用标记及属性
网页<body></body>常用标记及属性 <body></body>标记表示的是在整个浏览器内容框架中显示的部分. text属性用于控制HTML文档 ...
- qemu vm setup network(ssh) with buildroot
1, build buildroot with buildroot.config, that is 'make qemu_x86_64_defconfig' + some packages, sshd ...
- 浅谈AC自动机模板
什么是AC自动机? 百度百科 Aho-Corasick automaton,该算法在1975年产生于贝尔实验室,是著名的多模匹配算法. 要学会AC自动机,我们必须知道什么是Trie,也就是字典树.Tr ...
- Codeforces 990D - Graph And Its Complement
传送门:http://codeforces.com/contest/990/problem/D 这是一个构造问题. 构造一张n阶简单无向图G,使得其连通分支个数为a,且其补图的连通分支个数为b. 对于 ...
- 使用nfs3将hdfs挂载到本地或远程目录(非kerberos适用)
最基本的配置方法,aix.kerberos等的操作详见http://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-hdfs/Hdf ...
- 【Codeforces 479D】Long Jumps
[链接] 我是链接,点我呀:) [题意] 如果存在a[j]-a[i]=d 那么认为可以量出来长度d 现在给你量尺上的n个点. 问你最少要加多少个点,才能够量出来长度x和长度y [题解] 设dic1和d ...