实例化新 Android 片段的最佳实践 [英] Best practice for instantiating a new Android Fragment

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

问题描述

我见过两种在应用程序中实例化新 Fragment 的一般做法:

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 thought 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 do 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 决定稍后重新创建您的 Fragment,它将调用您的 Fragment 的无参数构造函数.所以重载构造函数不是解决办法.

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.

话虽如此,将内容传递给您的 Fragment 以便它们在 Android 重新创建 Fragment 后可用的方法是将包传递给 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);

即使 Android 以某种方式重新创建了 Fragment,此 Bundle 仍然可用.

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

另请注意:setArguments 只能在 Fragment 附加到 Activity 之前调用.

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

Android 开发者参考中也记录了这种方法:https://developer.android.com/reference/android/app/Fragment.html

This approach is also documented in the android developer reference: https://developer.android.com/reference/android/app/Fragment.html

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

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