关于fragment的构造函数问题

今天在写一个viewpager demo的时候,想定义一个fragment的有参数的构造函数,发现报错了,于是就学习一下关于fragment的构造函数的问题。

先列一下报的错:

  1. This fragment should provide a default constructor (a public constructor with no arguments) (com.example.TestFragment)
  2. 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()方法中,
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle bundle=getArguments();
    int flag=bundle.getInt("flag");
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章