在Android中實現輪播圖可以通過ViewPager和PagerAdapter來實現。以下是一個簡單的示例:
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="200dp"/>
public class MyPagerAdapter extends PagerAdapter {
private Context context;
private int[] images = {R.drawable.image1, R.drawable.image2, R.drawable.image3};
public MyPagerAdapter(Context context) {
this.context = context;
}
@Override
public int getCount() {
return images.length;
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view == object;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
imageView.setImageResource(images[position]);
container.addView(imageView);
return imageView;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView((View) object);
}
}
ViewPager viewPager = findViewById(R.id.viewPager);
MyPagerAdapter adapter = new MyPagerAdapter(this);
viewPager.setAdapter(adapter);
這樣就可以實現一個簡單的輪播圖效果了。如需實現無限循環輪播,可以在PagerAdapter中適當調整邏輯。