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

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

问题描述

我见过两种在应用程序中实例化新 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() 方法以在创建 Fragment 的新实例时提供灵活性 - 但我也可以通过为 Fragment 创建一个重载的构造函数来实现这一点.

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

即使 Fragment 以某种方式由 Android 重新创建,此 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 Fragment 的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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