viewPager + fragment

有两种实现方式,一种是 fragmentActivity + FragmentPagerAdapter (Fragment,FragmentManager需要导包:android.support.v4.app.)

另一种是 Activity + PagerAdapter(Fragment,FragmentManager需要导包:android.app.)

1. fragmentActivity + FragmentPagerAdapter

自定义FragmentPagerAdapter只需要重写: getItem(),getCount() 方法

2. Activity + PagerAdapter

自定义的 PagerAdapter 需要重写以下方法:

instantiateItem(ViewGroup, int)
destroyItem(ViewGroup, int, Object)  //记得删除 super.destroyItem(container, position, object);否则报异常:UnsupportedOperationException,原因查看源码
getCount()
isViewFromObject(View, Object)

 需要添加 Title 时还需要重写 getPageTitle() 方法

重写 :instantiateItem(ViewGroup, int)

        @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() 方法

使用FragmentTransaction,移除fragment时需要addtobackstack()否则无法回退(fragement 在移除时被销毁)

 

posted @ 2016-11-07 17:25  初心。。。  阅读(186)  评论(0编辑  收藏  举报