要实现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的滑动效果、添加指示器等。