今天在寫一個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()方法中,
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle=getArguments();
int flag=bundle.getInt("flag");
}