public class MyAdapter extends PagerAdapter {
private List<View> list;
private Context context;
public MyAdapter(List<View> list) {
this.list = list;
}
public MyAdapter(List<View> list, MainActivity mainActivity) {
this.list = list;
this.context = mainActivity;
}
@Override
public int getCount() {
return list.size();
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
// return super.instantiateItem(container, position);
View view = list.get(position);
container.addView(view);
return view;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
// super.destroyItem(container, position, object);
container.removeView(list.get(position));
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view==object;
}
}
如下是MainActivity的代码,上面是MyAdapter的代码。
list = new ArrayList<>();
list.add(LayoutInflater.from(this).inflate(R.layout.layout_a,null));
list.add(LayoutInflater.from(this).inflate(R.layout.layout_b,null));
list.add(LayoutInflater.from(this).inflate(R.layout.layout_c,null));
View view = LayoutInflater.from(this).inflate(R.layout.layout_d,null);
list.add(view);
myAdapter = new MyAdapter(list,this);
viewPager.setAdapter(myAdapter);
Android MyAdapter设置---芝麻博客