关于fragment的构造函数问题
2015-08-19 14:59
204 查看
今天在写一个viewpager demo的时候,想定义一个fragment的有参数的构造函数,发现报错了,于是就学习一下关于fragment的构造函数的问题。先列一下报的错:This fragment should provide a default constructor (a public constructor with no arguments) (com.example.TestFragment)Avoid non-default constructors in fragments: use a default constructor plus Fragment#setArguments(Bundle) instead首先,fragment必须要有一个无参的构造函数:public MyFragment(){}这样就解决了第一个错误然后,fragment不能直接定义有参的构造方法,要“曲线救国”一下:
public static MyFragment newInstance(int flag ,String name){ MyFragment fragment=new MyFragment(); Bundle bundle=new Bundle(); bundle.putInt("flag",flag); bundle.putString("name",name); fragment.setArguments(bundle); return fragment; }
最后在new fragment的时候:
MyFragment fragment=MyFragment.newInstance(1,"fragment1");
这样就最后完成了参数的传递
当然,在fragment中要使用这些参数时,可以在onCreate()方法中,
[code]public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle=getArguments(); int flag=bundle.getInt("flag");}[/code]
相关文章推荐
- 利用libavdecode进行视频码流的解码流程
- IOS开发 applicationDidBecomeActive 应用程序挂起、复原与终止
- POJ 1094 Sorting It All Out(拓扑排序·判断+实现)
- 数据结构 C语言实现选择排序
- 远程执行命令的psexec工具的基本使用——简单、强大
- 【POJ 1850】 Code
- (leetcode)Ugly Number
- Linux Tomcat 6.0安装配置实践总结
- viewpager获取当前view报空指针的解决方法
- matlab_无约束的非线性优化
- Android 不归路之广播BoradCast篇
- HDU 5400 Arithmetic Sequence(左d1等差右d2等差的区间个数)(枚举位置,求最大区间,算区间个数)
- LinearLayout、RelativeLayout、FrameLayout居中显示整理
- 为什么匿名内部类和局部内部类只能访问final变量
- Eclipse快捷键大全
- 我所认知的软件开发
- js中的json语法
- 利用grunt+browserify预编译js模板文件,支持commonJS加载
- JS提交对象数组到服务端的方法总结(C#实例)
- hdu4810 Wall Painting