官方的解释:
onCreate是指创建该fragment,类似于Activity.onCreate,你可以在其中初始化除了view之外的东西;
onCreateView是创建该fragment对应的视图,你必须在这里创建自己的视图并返回给调用者。
先看下Fragment的生命周期如图:
实现Fragment的UI必须实现的onCreateView()方法
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { View view= inflater.inflate(R.layout.xx, container,false); return view; }
onCreateView()中container参数代表该Fragment在Activity中的父控件;savedInstanceState提供了上一个实例的数据。
还有就是Fragment放入ViewPager 左右滑动的那种效果
mPager=(ViewPager) findViewById(R.id.viewpager); fragmentList=new ArrayList<Fragment>(); Fragment firstFragment=FragmentFactory.newInstance("this is first fragment"); Fragment secondFragment=FragmentFactory.newInstance("this is second fragment"); Fragment thirdFragment=FragmentFactory.newInstance("this is third fragment"); Fragment fourthFragment=FragmentFactory.newInstance("this is fourth fragment"); fragmentList.add(firstFragment); fragmentList.add(secondFragment); fragmentList.add(thirdFragment); fragmentList.add(fourthFragment);
public class FragmentFactory extends Fragment{ private String content; private String defaultContent="default content"; static FragmentFactory newInstance(String s){ FragmentFactory newFragment=new FragmentFactory(); Bundle bundle=new Bundle(); bundle.putString("content", s); newFragment.setArguments(bundle); return newFragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { Bundle args=getArguments(); content=args!=null?args.getString("content"):defaultContent; View view= inflater.inflate(R.layout.guide_2, container,false); TextView tv = (TextView) view.findViewById(R.id.tv); tv.setText(content); return view; } }
需要注意一点的是 FragmentFactory newFragment=new FragmentFactory(); 这个时候是还没有进入Fragment的生命周期,会进入构造方法,汗!一开始理解错了。
Fragment对象在ViewPager 容器里面,一次只能载入2个Fragment。