以下是一个示例代码,展示如何为多个ViewPager创建一个ImageAdapter:
首先,创建一个名为ImageAdapter的自定义适配器类:
public class ImageAdapter extends PagerAdapter {
private Context mContext;
private int[] mImages;
public ImageAdapter(Context context, int[] images) {
mContext = context;
mImages = images;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mImages[position]);
container.addView(imageView);
return imageView;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView((ImageView) object);
}
@Override
public int getCount() {
return mImages.length;
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view == object;
}
}
然后,在你的Activity或Fragment中,创建两个ViewPager,并为每个ViewPager设置一个ImageAdapter:
public class MainActivity extends AppCompatActivity {
private ViewPager mViewPager1, mViewPager2;
private ImageAdapter mAdapter1, mAdapter2;
private int[] mImages1 = {R.drawable.image1, R.drawable.image2, R.drawable.image3};
private int[] mImages2 = {R.drawable.image4, R.drawable.image5, R.drawable.image6};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager1 = findViewById(R.id.viewPager1);
mViewPager2 = findViewById(R.id.viewPager2);
mAdapter1 = new ImageAdapter(this, mImages1);
mAdapter2 = new ImageAdapter(this, mImages2);
mViewPager1.setAdapter(mAdapter1);
mViewPager2.setAdapter(mAdapter2);
}
}
最后,在你的布局文件中添加两个ViewPager:
这样,你就可以在一个Activity或Fragment中为两个ViewPager创建两个不同的适配器了。