为什么我要避免片段非默认的构造函数? [英] Why do I want to avoid non-default constructors in fragments?
问题描述
我创建一个应用程序与片段
并在其中的一个,我创建了一个非默认的构造函数,得到了这样的警告:
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.
这篇关于为什么我要避免片段非默认的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!