1.根据需求创建View,用集合把他们添加进去
例:
ArrayList<View> views = new ArrayList<>();
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
View pager1 = layoutInflater.inflate(R.layout.p15_pager_1, null);
views.add(pager1);
2.创建适配器,继承PagerAdapter。
例:
public class P15ViewPagerAdapter extends PagerAdapter {
private ArrayList<View>mViewArrayList;
P15ViewPagerAdapter(ArrayList<View> viewArrayList) {
mViewArrayList = viewArrayList;
}
@Override
public int getCount() {
return mViewArrayList.size();
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view==object;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
container.addView(mViewArrayList.get(position));
return mViewArrayList.get(position);
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView(mViewArrayList.get(position));
}
}
3.实现ViewPager.OnPageChangeListener接口并为Viewpager添加适配器
例:
binding.vpP15.setAdapter(new P15ViewPagerAdapter(views));
binding.vpP15.addOnPageChangeListener(this);
//只用到onPageSelected方法
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
binding.vpP15.setCurrentItem(position);
}
@Override
public void onPageScrollStateChanged(int state) {
}