实例化一个新的Andr​​oid碎片最佳实践 [英] Best practice for instantiating a new Android Fragment

查看:158
本文介绍了实例化一个新的Andr​​oid碎片最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了两种通用的做法来实例化应用程序中的新片段:

I have seen two general practices to instantiate a new Fragment in an application:

Fragment newFragment = new MyFragment();

Fragment newFragment = MyFragment.newInstance();

第二个方案是利用一个静态方法的newInstance()一般的包含下面的方法。

The second option makes use of a static method newInstance() and generally contains the following method.

public static Fragment newInstance() 
{
    MyFragment myFragment = new MyFragment();
    return myFragment;
}

起初,我虽然主要好处是事实,我可以重载newInstance()方法创建一个片段的新实例时给予的灵活性 - 但我还可以通过创建一个重载的构造函数片段

At first I though the main benefit was the fact that I could overload the newInstance() method to give flexibility when creating new instances of a Fragment - but I could also this by creating an overloaded constructor for the Fragment.

难道我们错过了什么?

什么是一种方法比其他的好处?还是只是好的做法呢?

What are the benefits of one approach over the other? Or is it just good practice?

推荐答案

如果Android的决定以后重新创建片段,它会打电话给你片段的无参数的构造函数。所以超载的构造是不是一个解决方案。

If Android decides to recreate your Fragment later, it's going to call the no-argument constructor of your fragment. So overloading the constructor is not a solution.

有了这样说,传递东西的片段,使它们可经过片段是由Android的重建是通过捆绑到 setArguments 法的方式

With that being said, the way to pass stuff to your Fragment so that they are available after a Fragment is recreated by Android is to pass a bundle to the setArguments method.

所以,举例来说,如果我们想要一个整数传递到我们会使用类似的片段:

So, for example, if we wanted to pass an integer to the fragment we would use something like:

public static MyFragment newInstance(int someInt) {
    MyFragment myFragment = new MyFragment();

    Bundle args = new Bundle();
    args.putInt("someInt", someInt);
    myFragment.setArguments(args);

    return myFragment;
}

和后来的片段的onCreate()您可以通过使用访问该整数:

And later in the Fragment onCreate() you can access that integer by using:

getArguments().getInt("someInt", 0);

这包将可即使片段是由机器人在某种程度上重建。

This Bundle will be available even if the Fragment is somehow recreated by Android.

还要注意:前片段附着到活动setArguments只能被称为

Also note: setArguments can only be called before the Fragment is attached to the Activity.

这篇关于实例化一个新的Andr​​oid碎片最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆