为什么我要避免片段非默认的构造函数?我要、函数、片段

由网友(薄荷绿)分享简介:我创建一个应用程序与片段并在其中的一个,我创建了一个非默认的构造函数,得到了这样的警告:I am creating an app with Fragments and in one of them, I created a non-default constructor and got this warning:A...

我创建一个应用程序与片段并在其中的一个,我创建了一个非默认的构造函数,得到了这样的警告:

I am creating an app with Fragments and in one of them, I created a non-default constructor and got this warning:

Avoid non-default constructors in fragments: use a default constructor plus Fragment#setArguments(Bundle) instead

谁能告诉我,为什么这不是一个好主意?

Can someone tell me why this is not a good idea?

您可以还建议我将如何做到这一点:

Can you also suggest how I would accomplish this:

public static class MenuFragment extends ListFragment {
    public ListView listView1;
    Categories category;

    //this is my "non-default" constructor
    public MenuFragment(Categories category){
        this.category = category;
    }....

在不使用非默认的构造函数?

Without using the non-default constructor?

推荐答案

请捆绑对象,并插入(在本例中您的类别对象)的数据。要小心,你不能直接传递这个对象进入包,除非它是序列化。 我觉得这是更好地建立自己的对象中的片段,并把唯一的ID或其他什么东西的线束。这是code创建和附加包:

Make a bundle object and insert your data (in this example your Category object). Be careful, you can't pass this object directly into the bundle, unless it's serializable. I think it's better to build your object in the fragment, and put only an id or something else into bundle. This is the code to create and attach a bundle:

Bundle args = new Bundle();
args.putLong("key", value);
yourFragment.setArguments(args);

此后,在您的片段的访问数据:

After that, in your fragment access data:

Type value = getArguments().getType("key");

这就是全部。

That's all.

阅读全文

相关推荐

最新文章