viewpager实现翻页效果(fragment)

viewpager的运用核心在于适配器的编写,及最终的setadapter(adapter)
谷歌官方认为,ViewPager应该和Fragment一起使用时,此时ViewPager的适配器是FragmentPagerAdapter,当你实现一个FragmentPagerAdapter,你必须至少覆盖以下方法:

getCount()

getItem()

如果ViewPager没有和Fragment一起,ViewPager的适配器是PagerAdapter,它是基类提供适配器来填充页面ViewPager内部,当你实现一个PagerAdapter,你必须至少覆盖以下方法:

instantiateItem(ViewGroup, int)
destroyItem(ViewGroup, int, Object)
getCount()
isViewFromObject(View, Object)

public class NewTitleAdapter extends FragmentPagerAdapter {
    ArrayList arrayList;
    public NewTitleAdapter(FragmentManager fm, ArrayList myarrayList) {
        super(fm);
        this.arrayList=myarrayList;

    }

    @Override
    public Fragment getItem(int position) {
        return (Fragment) arrayList.get(position);
    }

    @Override
    public int getCount() {
        return arrayList.size();
    }
}

activity里:

fram1=new TypeFragment().newInstance(id);
                fragmentlist.add(fram1);
   myTitleAdapter=new NewTitleAdapter(getSupportFragmentManager(),(ArrayList)fragmentlist);
            mViewPager.setAdapter(myTitleAdapter);

此外,还可以设置fragment监听事件:

  mViewPager.setCurrentItem(0);
            mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {


                }

                @Override
                public void onPageSelected(int position) {
                    btn_change(position + 1);
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });

activity添加一个viewpager即可。

你可能感兴趣的:(Android)