为什么我想避免片段中的非默认构造函数? [英] Why do I want to avoid non-default constructors in fragments?
问题描述
我正在使用 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?
推荐答案
制作一个 bundle 对象并插入你的数据(在这个例子中是你的 Category
对象).请注意,您不能将此对象直接传递到包中,除非它是可序列化的.我认为最好在片段中构建您的对象,并且只将一个 id 或其他东西放入包中.这是创建和附加包的代码:
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");
仅此而已.
这篇关于为什么我想避免片段中的非默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!