我正在使用Fragments
创建一个应用程序,在其中一个应用程序中,我创建了一个非默认构造函数,并收到以下警告:
Avoid non-default constructors in fragments: use a default constructor plus Fragment#setArguments(Bundle) instead
谁能告诉我为什么这不是个好主意?
你也可以建议我如何做到这一点:
public static class MenuFragment extends ListFragment {
public ListView listView1;
Categories category;
//this is my "non-default" constructor
public MenuFragment(Categories category){
this.category = category;
}....
而不使用非默认构造函数?
发布于 2012-08-22 06:08:51
创建一个包对象并插入您的数据(在本例中是您的Category
对象)。请注意,您不能将此对象直接传递到bundle中,除非它是可序列化的。我认为更好的做法是在片段中构建对象,并只将id或其他内容放入包中。下面是创建和附加bundle的代码:
Bundle args = new Bundle();
args.putLong("key", value);
yourFragment.setArguments(args);
之后,在您的片段访问数据中:
Type value = getArguments().getType("key");
就这样。
发布于 2013-04-17 00:53:58
似乎没有一个答案真正回答了“为什么使用bundle传递参数而不是非默认构造函数”。
之所以应该通过捆绑包传递参数,是因为当系统恢复fragment
时(例如,在配置更改时),它将自动恢复您的bundle
。
像onCreate
或onCreateView
这样的回调应该从bundle
中读取参数-这样就可以保证将fragment
的状态正确地恢复到初始化fragment
时所使用的状态(请注意,此状态可以与传递给onCreate/onCreateView
的onSaveInstanceState bundle
不同)
使用静态newInstance()
方法的推荐只是一个推荐。您可以使用非默认构造函数,但请确保在该构造函数的主体内的bundle
中填充了初始化参数。并在onCreate()
或onCreateView()
方法中读取这些参数。
发布于 2013-03-25 17:58:20
由于FragmentManager
实例化它的方式,你的Fragment
不应该有构造函数。您应该有一个使用所需参数定义的newInstance()
静态方法,然后将它们捆绑在一起,并将它们设置为片段的参数,稍后可以使用Bundle
参数访问这些参数。
例如:
public static MyFragment newInstance(int title, String message) {
MyFragment fragment = new MyFragment();
Bundle bundle = new Bundle(2);
bundle.putInt(EXTRA_TITLE, title);
bundle.putString(EXTRA_MESSAGE, message);
fragment.setArguments(bundle);
return fragment ;
}
并在onCreate
上阅读这些论点
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
title = getArguments().getInt(EXTRA_TITLE);
message = getArguments().getString(EXTRA_MESSAGE);
//...
}
这样,如果分离并重新附加,则可以通过参数存储对象状态,这与附加到Intent
的bundles
非常相似。
https://stackoverflow.com/questions/12062946
复制相似问题