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 ...
随机推荐
- LN : leetcode 513 Find Bottom Left Tree Value
lc 513 Find Bottom Left Tree Value 513 Find Bottom Left Tree Value Given a binary tree, find the lef ...
- 2017-12-04HTML table布局
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...
- 通过机智云APP来学习安卓
效果非常之好,安卓6.0之后就进行了动态授权.按照网上的视频一步一步调试的非常成功,非常舒服.
- EditPlus里面自带有更改文件编码的功能
- 安装好Pycharm后如何配置Python解释器简易教程
呃呃,遇到坑了...... 安装完Python,没有去配置好Python解释器,直接打开Python项目包,去运行程序,程序输出结果只是显示 Process finished with exit co ...
- 使用Unittest做单元测试,addTest()单个case的时候却执行全部的case
参考: http://tieba.baidu.com/p/6008699660 首先造成这个结果的原因是pycharm配置问题 问题验证: 测试代码: import unittest class Te ...
- Vue指令2:v-bind
v-bind 指令可以更新 HTML 属性: <a v-bind:href="url">...</a> 在这里 href 是参数,告知 v-bind 指令将 ...
- 梦想CAD控件COM接口标注样式
增加标注样式 用户可以增加标注样式到数据库,具体实现c#代码如下: private void CreateDim() { //返回控件的数据库对象 MxDrawDatabase database = ...
- JavaScipt30(第十个案例)(主要知识点:选中一个数组中间相连部分进行操作的一种思路)
承接上文,第九个案例就不说了,是控制台的一些东西,一般用的很少,了解下就行了,想用的时候再翻api.这是第10个案例: 需要实现的效果是:点击一个checkbox,然后按下shift点击另一个chec ...
- java中的数学函数Math方法记录
1,三角函数与属性Math.sin() -- 返回数字的正弦值Math.cos() -- 返回数字的余弦值Math.tan() -- 返回数字的正切值Math.asin() -- 返回数字的反正弦值M ...