首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >创建片段:构造函数vs newInstance()

创建片段:构造函数vs newInstance()
EN

Stack Overflow用户
提问于 2013-02-02 04:50:07
回答 1查看 32K关注 0票数 58

最近,我厌倦了在创建Fragments时必须不断地知道String键才能将参数传递给Bundles。因此,我决定为我的Fragments创建构造函数,它将接受我想要设置的参数,并使用正确的String键将这些变量放入Bundles中,从而消除了其他FragmentsActivities需要知道这些键的需要。

代码语言:javascript
复制
public ImageRotatorFragment() {
    super();
    Log.v(TAG, "ImageRotatorFragment()");
}

public ImageRotatorFragment(int imageResourceId) {
    Log.v(TAG, "ImageRotatorFragment(int imageResourceId)");

    // Get arguments passed in, if any
    Bundle args = getArguments();
    if (args == null) {
        args = new Bundle();
    }
    // Add parameters to the argument bundle
    args.putInt(KEY_ARG_IMAGE_RES_ID, imageResourceId);
    setArguments(args);
}

然后我像往常一样拉出这些论点。

代码语言:javascript
复制
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.v(TAG, "onCreate");

    // Set incoming parameters
    Bundle args = getArguments();
    if (args != null) {
        mImageResourceId = args.getInt(KEY_ARG_IMAGE_RES_ID, StaticData.getImageIds()[0]);
    }
    else {
        // Default image resource to the first image
        mImageResourceId = StaticData.getImageIds()[0];
    }
}

然而,林特对此提出了异议,他说没有带有其他参数的构造函数的Fragment的子类,甚至需要我使用@SuppressLint("ValidFragment")来运行应用程序。问题是,这段代码运行得非常好。我可以使用ImageRotatorFragment(int imageResourceId)或老方法ImageRotatorFragment(),并对其手动调用setArguments()。当Android需要重新创建片段时(方向改变或内存不足),它会调用ImageRotatorFragment()构造函数,然后传递与我的值相同的参数Bundle,这些值被正确设置。

因此,我一直在搜索“建议”的方法,并看到许多使用newInstance()创建带参数的Fragments的示例,这似乎与我的构造函数做的事情是一样的。所以我自己做了测试,它和以前一样完美无瑕,除了Lint对它的抱怨。

代码语言:javascript
复制
public static ImageRotatorFragment newInstance(int imageResourceId) {
    Log.v(TAG, "newInstance(int imageResourceId)");

    ImageRotatorFragment imageRotatorFragment = new ImageRotatorFragment();

    // Get arguments passed in, if any
    Bundle args = imageRotatorFragment.getArguments();
    if (args == null) {
        args = new Bundle();
    }
    // Add parameters to the argument bundle
    args.putInt(KEY_ARG_IMAGE_RES_ID, imageResourceId);
    imageRotatorFragment.setArguments(args);

    return imageRotatorFragment;
}

我个人发现使用构造函数比使用newInstance()和传递参数要普遍得多。我相信你可以在Activities中使用同样的构造函数技术,Lint不会对此抱怨。所以基本上我的问题是,为什么谷歌不希望你对Fragments**?** 使用带参数的构造函数

我唯一的猜测是,这样您就不会在不使用Bundle的情况下尝试设置实例变量,因为在重新创建Fragment时不会设置该变量。通过使用static newInstance()方法,编译器不允许您访问实例变量。

代码语言:javascript
复制
public ImageRotatorFragment(int imageResourceId) {
    Log.v(TAG, "ImageRotatorFragment(int imageResourceId)");

    mImageResourceId = imageResourceId;
}

我仍然不认为这是禁止在构造函数中使用参数的足够理由。其他人对此有什么见解吗?

EN

回答 1

Stack Overflow用户

发布于 2016-07-08 19:38:20

Android只会使用默认构造函数重新创建它杀死的片段,所以我们在其他构造函数中所做的任何初始化都将是lost.Hence数据将丢失。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14654766

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档