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 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_my);

        // 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 withgetArguments() 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 callinggetActivity().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
    }

}

Android:Bundles in Activities and Fragments,布布扣,bubuko.com

时间: 2024-12-21 05:28:45

Android:Bundles in Activities and Fragments的相关文章

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

Android Do not keep activities选项分析

Android Do not keep activities选项分析 Developer Options里面有一项: Do not keep activities -> 不保留Activities. 默认是不开启的. 当开启之后,用户离开后即销毁每个Activity. 相关背景知识: task, back stack和低内存时的系统行为 当用户开启一个task,里面的activities都会被保存在这个栈的back stack中. 当前的activity在栈顶并且拥有焦点,之前的activiti

Android: Failure [INSTALL_FAILED_DEXOPT] and Failure [INSTALL_FAILED_UID_CHANGED] 解决方案

1. 错误:  Failure [INSTALL_FAILED_DEXOPT]  Android安装App时 D:\WorkSpace\Administrator\workspace\svn\sootOutput>adb install OpenSudoku_1.apk 1032 KB/s (235960 bytes in 0.223s) pkg: /data/local/tmp/OpenSudoku_1.apkFailure [INSTALL_FAILED_UID_CHANGED] 原因是:

Android:ViewPager扩展详解——带有导航的ViewPagerIndicator(附带图片缓存,异步加载图片)

大家都用过viewpager了, github上有对viewpager进行扩展,导航风格更加丰富,这个开源项目是ViewPagerIndicator,很好用,但是例子比较简单,实际用起来要进行很多扩展,比如在fragment里进行图片缓存和图片异步加载. 下面是ViewPagerIndicator源码运行后的效果,大家也都看过了,我多此一举截几张图: 下载源码请点击这里 ===========================================华丽的分割线==============

Android:远程服务Service(含AIDL & IPC讲解)

前言 Service作为Android四大组件之一,应用非常广泛 本文将介绍Service其中一种常见用法:远程Service 如果你对Service还未了解,建议先阅读我写的另外一篇文章: Android四大组件:Service史上最全面解析 目录 1. 远程服务与本地服务的区别 远程服务与本地服务最大的区别是:远程Service与调用者不在同一个进程里(即远程Service是运行在另外一个进程):而本地服务则是与调用者运行在同一个进程里 二者区别的详细区别如下图: 2. 使用场景 多个应用程

Android:(本地、可通信的、前台、远程)Service使用全面介绍

前言 Service作为Android四大组件之一,应用非常广泛 本文将介绍Service最基础的知识:Service的生命周期 如果你对Service还未了解,建议先阅读我写的文章: Android四大组件:Service史上最全面解析 目录 1. Service分类 1.1 Service的类型 1.2 特点 2.具体使用解析 2.1 本地Service 这是最普通.最常用的后台服务Service. 2.1.1 使用步骤 步骤1:新建子类继承Service类 需重写父类的onCreate()

Android:调用webservice详解;

很多时候要用到android端调用webservice服务, 下面例子就是调用webservice 以及对流的多种方式处理: package com.example.android_webservice; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputSt

[活动已结束]《深入理解Android:Wi-Fi、NFC和GPS卷》CSDN社区活动

今天有一个CSDN社区活动,解答关于Android系统的学习.认识.开发等方面的问题,并就<深入理解Android:Wi-Fi.NFC和GPS卷>一书为大家答疑解惑,了解Android Framework的实现原理.活动链接:http://bbs.csdn.net/topics/390765275?page=1#post-397228045 此次活动已经完结,谢谢各位的支持.获奖的三位兄弟是: 以下欢迎大家踊跃提问,在本帖回复就可以,參与活动并提出问题就可以获得100可用分.在大家的积极參与下

[转]Android:布局实例之模仿QQ登录界面

Android:布局实例之模仿QQ登录界面 预览图: 准备: 1.找到模仿对象 QQ登陆界面UI下载>>>>> 2.导入工程 3.查看布局结构和使用控件 其对应效果图分布为 4.分析样式选择器 下拉箭头2种样式:点击和默认状态 文本框2种样式:聚焦和默认状态 复选框3种样式:选择.不选择和鼠标点着不放 左下角按钮2种样式:点击和默认 登录按钮2样式:点击和默认 ============================================帖代码===========