Fragment传递参数

不问归期 提交于 2020-01-16 07:15:20

实例化自定义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

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!