ViewPager + Fragment实现滑动页面

文章目录

  • 建立ViewPager的Fragment适配器FragmentPagerAdapter
  • 添加fragment
  • 重写ViewPager的监听器
  • 绑定ViewPager控件并添加适配器、监听器

建立ViewPager的Fragment适配器FragmentPagerAdapter

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;

public class NewsViewPagerAdapter extends FragmentPagerAdapter {
   List<Fragment> fragmentList = new ArrayList<Fragment>();
   public NewsViewPagerAdapter(FragmentManager fm,List<Fragment> fragmentList) {
       super(fm);
       this.fragmentList = fragmentList;
   }
   @Override
   public Fragment getItem(int position) {
       return fragmentList.get(position);
   }
   @Override
   public int getCount() {
       return fragmentList.size();
   }
}

添加fragment

注意库引用要与适配器中的库一致

import android.support.v4.app.Fragment;
List<Fragment> fragments = new ArrayList<>();
fragments.add(new ArticleFragment());
fragments.add(new VideoFragment());

重写ViewPager的监听器

绑定ViewPager控件并添加适配器、监听器

ViewPager vp;
vp=(ViewPager)findViewById(R.id.vp);
vp.setAdapter(new NewsViewPagerAdapter(getSupportFragmentManager(),fragments));
vp.setOnPageChangeListener(this);
vp.setCurrentItem(0);

注意:getSupportFragmentManger()函数要在Activity继承FragmentActivity或者AppCompatActivity后才能使用

你可能感兴趣的:(android)