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 ...
随机推荐
- HTTP的报文格式、GET和POST格式解析
1. HTTP报文格式 HTTP报文是面向文本的,报文中的每一个字段都是一些ASCII码串,各个字段的长度是不确定的.HTTP有两类报文:请求报文和响应报文.请求报文一个HTTP请求报文由请求行(re ...
- springboot项目中,@transactional 无效
问题: springboot项目,依然是使用jpa.Hibernate来操作mysql,涉及到数据库的操作,就少不了事务.写了一个接口,用来测试@Transaction注解的作用,发现没有效果 分析: ...
- JDBC更新10W级以上数据性能优化
随笔缘由: 系统完成到一定程度,少不了要往数据库中添加大量数据进行性能测试. 我用程序做数据10W条,使用jdbc批更新的API,发现每次只能插入2W多条记录. 一番小小研究,觉得总结一下可能有些意义 ...
- PHP——基本使用(二)
PHP与Apache Apache服务器在接受到客户端请求的时候,根据客户端所请求的文件的类型,然后去问模块能否处理此文件,php作为模块之一有可能可以处理此文件,处理之后将数据再返回给apache, ...
- Farseer.net轻量级开源框架 入门篇:分类逻辑层
导航 目 录:Farseer.net轻量级开源框架 目录 上一篇:Farseer.net轻量级开源框架 入门篇: 缓存逻辑层 下一篇:Farseer.net轻量级开源框架 入门篇: 添加数据详解 ...
- 场景分割:MIT Scene Parsing 与DilatedNet 扩展卷积网络
MIT Scene Parsing Benchmark简介 Scene parsing is to segment and parse an image into different image re ...
- POJ_1611_The Suspect
The Suspects Time Limit: 1000MS Memory Limit: 20000K Total Submissions: 25149 Accepted: 12329 De ...
- C语言编辑编译及集成开发环境
C语言编辑编译及集成开发环境 编辑器 在不同的操作系统上使用不同的编辑器,保存源代码文件时,文件名应指出程序的功能扩展名应为.c. 编译器 编译器把源代码编译成机器语言的二进制指令即目标代码生成目标文 ...
- xmpp聊天室(5)
聊天室 //初始化聊天室 XMPPJID *roomJID = [XMPPJID jidWithString:ROOM_JID]; xmppRoom = [[XMPPRoom alloc] initW ...
- 07Html、CSS
07Html.CSS-2018/07/17 1.HTML是用来描述网页的一种标记语言,是一套标记标签.HTML用使用标记标签来描述网页.超文本 标记语言. 2.格式 <html> < ...