viewPager在开发中是不少用到的,每个ViewPager都需要对应的Adapter,很简单,直接看代码:
首先,新建一个类集成 PagerAdapter,如下:
public class GiveAwayViewPagerAdapter extends PagerAdapter {
private ArrayList<User> list;
private Context mContext;
public GiveAwayViewPagerAdapter(ArrayList<User> list, Context mContext) {
this.list = list;
this.mContext = mContext;
}
@Override
public int getCount() {
return list.size();
}
/**
* 判断instantiateItem(ViewGroup container, int position)返回的要加载的pager对象是不是view视图,
* 是则返回true并显示,不是返回false不显示。
*/
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
//初始化并加载文件
@Override
public Object instantiateItem(ViewGroup container, int position) {
View view = LayoutInflater.from(container.getContext()).inflate(R.layout.item_head_assets_give_away, container, false);
//此处为对应的控制逻辑
container.addView(view);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// super.destroyItem(container, position, object);
container.removeView((View) object);
}
}
最后就是绑定viewPager了。
val adapter = GiveAwayViewPagerAdapter(users, host)
host.rv_head.adapter = adapter
END