activities和fragments中Bundle的处理

来源:  http://blog.petrnohejl.cz/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. 

Bundle是一个非常有用且可以通过String值映射各种Parcelable类型的数据持有者。可以这么认为Bundle就是一个异源的键值表。

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.

Bundle 经常被用于Intents,Activities 和Fragments传递数据。我想描述在Android中我是如何使用Bundles的,并且向你们展示一些好的技巧。

Activity

When you are creating a new instance of Activity via Intent, you can pass some extra data to the Activity. 

当你通过Intent创建一个新的Activity实例,你可以传递而外的数据给这个Activity。

Data are stored in Bundle and can be retrieved calling  getIntent().getExtras().

数据被保存在Bundle中,且可以通过调用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. 

这是一个好的练习去实现  能够返回一个可以启动Activity的Intent 静态newIntent()方法。

This way you have compile time checking for the arguments passed to the Activity. This pattern is suitable for Service and Broadcast as well.

这样你在编译时检查传递给Activity的参数。这种模式也适用于服务和广播。

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.

Bundle也经常被用于保持当前状态的活动实例的重新初始化( 例如。配置的改变)。

 You can supply some data in onSaveInstanceState(Bundle) and retrieve them back in onCreate(Bundle) method or onRestoreInstanceState(Bundle)

你可以提供一些数据在onSaveInstanceState(Bundle)方法,恢复数据在onCreate(Bundle) 

或者onRestoreInstanceState(Bundle).

Main difference between these methods is that onRestoreInstanceState(Bundle) is called after onStart()

这两个方法最主要的不同在于onRestoreInstanceState(Bundle) 调用在 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.

看下面的例子。注意,EXTRA_PRODUCT_ID常数是公开的。那是因为我们需要它在一个Fragment封装在这个活动。

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. 

当你创建一个Fragment实例,你能通过setArguments(Bundle)方法传递参数。

Data can be retrieved withgetArguments() method. It would be a mistake to supply initialization data through an overloaded constructor. 

数据通过getArguments() 被恢复。它将是一个错误 即通过一个重载的构造函数提供数据初始化。

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实例能被重建(例如.配置变化)导致丢失数据,因为在重新初始化Fragment时调用时不会调用带额外参数构造函数。

 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 

只会调用空的构造函数。解决这个问题的最好方法是实现静态创建方法newInstance ,它能返回一个新的Fragment实例且 通过setArguments(Bundle)渠道设置参数。

the arguments via setArguments(Bundle).

Fragment state can be saved using onSaveInstanceState(Bundle) method. It is similar to the Activity. Data can be restored

方法onSaveInstanceState(Bundle)能够保存状态Fragment状态。这个与Activity相似。

 in onCreate(Bundle),onCreateView(LayoutInflater, ViewGroup, Bundle)onActivityCreated(Bundle) or onViewStateRestored(Bundle) methods.

数据能onCreate(Bundle),onCreateView(LayoutInflater, ViewGroup, Bundle)onActivityCreated(Bundle)或者onViewStateRestored(Bundle) 时被还原。

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().

在创建Activity实例时Fragment也能访问被传递的Intent extras。你能通过通过调用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
    }
}


你可能感兴趣的:(activities和fragments中Bundle的处理)