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.

时间: 2024-08-24 14:45:38

Handling bundles in activities and fragments的相关文章

Android:Bundles in Activities and Fragments

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 new

Android Handling back press when using fragments in Android

In MainActivity: getSupportFragmentManager().beginTransaction().replace(R.id.gif_contents, gifPageTwoFragment, "gifPageTwoFragment").addToBackStack("gifPageTwoFragment").commit(); In GifPageTwoFragment: @Override public void onActivity

5.User Interface/ActionBar

1. ActionBar First added in Android 3.0(API level 11) 2. Working the Action Bar 2.1 Removing the action bar ActionBar actionBar = getSupportActionBar(); actionBar.hide(); 2.2 Using a logo instead of an icon By default, the system uses your applicatio

android 消息传递机制EventBus的深入探究

以前,对于activity和fragment之间的通信可以使用接口的方式,定义起来比较麻烦费事,偶然间发现可以使用EventBus,发现很好用,查看了一下官方说明:EventBus是针一款对Android的发布/订阅事件总线.它可以让我们很轻松的实现在Android各个组件之间传递消息,并且代码的可读性更好,耦合度更低.但是在用的过程中总会出现一些问题,下面就将出现的问题详细记录一下,顺便具体学习EventBus(GreenRobot)这个第三方开源库,了解它内部的实现原理,以至于出了问题可以快

【转载】安卓APP架构

注:本篇博文转载于 http://my.oschina.net/mengshuai/blog/541314?fromerr=z8tDxWUH 本文介绍了文章作者从事了几年android应用的开发,经历2次架构变革,第一次集成了RxJava第二次集成了MVP,并将RxJava与MVP完美结合,实现了低耦合,代码简单,测试方便的架构. 其实我们在开发中也遇到过,Android入门门槛较低,如果前期对APP规划不清晰,Coder们对未来变化把握不准,技术架构经验不够强大,最终导致就是一个Activit

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 icon Adding Action Items Handling clicks on action items Using split action bar Navigating Up with the App Icon Adding an Action View Handling collap

EventBus 3.0使用与源码分析

EventBus简介 EventBus is a publish/subscribe event bus optimized for Android. EventBus 是一个基于发布/订阅模式的事件总线.其模型图如下 从图可知,EventBus分为四个角色,消息发布者.事件总线.事件.消息订阅者.消息发布者把Event(消息)post(发送)到事件总线,事件总线维护一个事件队列,把Event发送到Subscriber(消息订阅者),调用其onEvent方法进行相应的处理. 1.特点 - 简化组

Square 开源库Flow和Mortar的介绍

原文链接 : Architecting An Investigation into Flow and Mortar 译者 : sundroid( chaossss 协同翻译) 校对者: chaossss.Mr.Simple 状态 : 完成 "在 App 开发过程中尽可能使用 Fragment 替代 Activity",Google 官方的这个建议无疑让万千 Android 开发者开始关注.使用 Fragment.但随着使用 Fragment 的人数增多,Fragment 存在的各种问题

Using lists in Android (ListView) - Tutorial

Lars Vogel Version 4.6 Copyright © 2010, 2011, 2012, 2013, 2014 vogella GmbH 20.11.2014 Using Android ListView, ListActivity and ListFragment This tutorial describes how to use the ListView view together with Activities and Fragments in Android. The