关于Android Fragment初始化

时间:2022-05-06 19:40:04

  看了很多大神写的东西,发现Fragment的创建(New) 都是在自身的类中创建一个instance方法,具体方法如下:


public class PageFragment extends Fragment {

public static final PageFragment newInstance(String title, int resImageId){
PageFragment f = new PageFragment();
Bundle bdl = new Bundle(1);
bdl.putString(TITLE, title);
bdl.putInt(IMAGE, resImageId);
f.setArguments(bdl);
return f;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
title = getArguments().getString(TITLE);
resImageId = getArguments().getInt(IMAGE);
Log.d(TAG, title + " - onCreate");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(TAG, title + " - onCreateView");
return inflater.inflate(R.layout.myfragment, container, false);
}

}

这种写法有什么好处呢?

1.方便初始化,需要什么参数一目了然2.Bundle附加参数的key值不需要Activity和Fragment统一,减少出错概率。