要實現Android輪播圖,可以使用ViewPager和PagerAdapter來實現。以下是一個簡單的示例代碼:
public class SlideshowAdapter extends PagerAdapter {
private Context mContext;
private List<Integer> mImageList;
public SlideshowAdapter(Context context, List<Integer> imageList) {
mContext = context;
mImageList = imageList;
}
@Override
public int getCount() {
return mImageList.size();
}
@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(mContext);
imageView.setImageResource(mImageList.get(position));
container.addView(imageView);
return imageView;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView((View) object);
}
}
public class MainActivity extends AppCompatActivity {
private ViewPager mViewPager;
private List<Integer> mImageList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = findViewById(R.id.viewPager);
mImageList = new ArrayList<>();
// 添加圖片資源到mImageList
mImageList.add(R.drawable.image1);
mImageList.add(R.drawable.image2);
mImageList.add(R.drawable.image3);
SlideshowAdapter adapter = new SlideshowAdapter(this, mImageList);
mViewPager.setAdapter(adapter);
}
}
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_centerInParent="true" />
這樣就實現了一個簡單的Android輪播圖。你可以根據需要自定義ViewPager的滑動效果、添加指示器等。