有兩種實現方式,一種是 fragmentActivity + FragmentPagerAdapter (Fragment,FragmentManager須要導包:android.support.v4.app.)java
另外一種是 Activity + PagerAdapter(Fragment,FragmentManager須要導包:android.app.)android
1. fragmentActivity + FragmentPagerAdapterapp
自定義FragmentPagerAdapter只須要重寫: getItem(),getCount() 方法ide
2. Activity + PagerAdapterspa
自定義的 PagerAdapter 須要重寫如下方法:code
instantiateItem(ViewGroup, int)
destroyItem(ViewGroup, int, Object) //記得刪除 super.destroyItem(container, position, object);不然報異常:UnsupportedOperationException,緣由查看源碼
getCount()
isViewFromObject(View, Object)
須要添加 Title 時還須要重寫 getPageTitle() 方法blog
重寫 :instantiateItem(ViewGroup, int)get
@Override public Object instantiateItem(ViewGroup container, int position) { Fragment fragment = mList.get(position); if (!fragment.isAdded()) { FragmentTransaction saction = mFragManager.beginTransaction(); saction.add(fragment, fragment.getClass().getSimpleName()); //只有commit纔會執行 saction.commit(); //executePendingTransactions--當即執行 mFragManager.executePendingTransactions(); } View view = fragment.getView(); container.addView(view); return view; }
重寫 :isViewFromObject(View, Object)源碼
@Override public boolean isViewFromObject(View view, Object object) { return view == object; }
注意:自定義Fragemt 時,必須重寫 onCreateView() 方法it
使用FragmentTransaction,移除fragment時須要addtobackstack()不然沒法回退(fragement 在移除時被銷燬)