您的位置:首页 > 其它

关于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]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: