实例化自定义Fragment时,为什么官方推荐Fragment.setArguments(Bundle bundle)这种方式来传递参数,而不推荐通过构造方法直接来传递参数呢。
在使用构造函数时候遇到这样错误提示:Fragments should be static such that they can be re-instantiated by the system, and anonymous classes are not static
所以这边就记录下使用Fragment.setArguments(Bundle bundle)这种方式来传递参数的用法
创建newInstance方法
public static final BeautyOrderItemFragment newInstance(int orderId, String title)
{
BeautyOrderItemFragment fragment = new BeautyOrderItemFragment();
Bundle bundle = new Bundle();
bundle.putInt("orderId",orderId);
bundle.putString("title", title);
fragment.setArguments(bundle);
return fragment ;
}
重写onCreate
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTitle=getArguments().getString("title");
mOrderId=getArguments().getInt("orderId");
}
创建fragment实例
BeautyOrderItemFragment beautyOrderItemFragment=BeautyOrderItemFragment.newInstance(1,"测试订单");
附加个参考链接,感觉大牛的总结让我少走了很多弯路 http://blog.csdn.net/tu_bingbing/article/details/24143249