1.添加依赖:
在你的build.gradle文件中添加ViewPager2的依赖:
implementation 'androidx.viewpager2:viewpager2:1.0.0'
2.布局文件:
在你的布局文件中添加ViewPager2组件:
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/viewPager2"
android:layout_width="match_parent"
android:layout_height="match_parent" />
3.创建适配器:
创建一个继承自RecyclerView.Adapter的适配器来管理ViewPager2中的页面:
public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.GalleryViewHolder> {
private List<Bitmap> images;
public GalleryAdapter(List<Bitmap> images) {
this.images = images;
}
@NonNull
@Override
public GalleryViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_gallery, parent, false);
return new GalleryViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull GalleryViewHolder holder, int position) {
holder.imageView.setImageBitmap(images.get(position));
}
@Override
public int getItemCount() {
return images.size();
}
static class GalleryViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
GalleryViewHolder(View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
}
}
}
4.设置3D转换效果:
为ViewPager2设置一个PageTransformer来实现3D效果:
viewPager2.setPageTransformer(new ViewPager2.PageTransformer() {
@Override
public void transformPage(@NonNull View page, float position) {
final float MIN_SCALE = 0.75f;
final float MIN_ALPHA = 0.5f;
if (position < -1) { // [-Infinity,-1)
// Page is completely off-screen to the left.
page.setAlpha(0);
} else if (position <= 1) { // [-1,1]
// Modify the default slide transition to shrink the page as well
float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
float vertMargin = page.getHeight() * (1 - scaleFactor) / 2;
float horzMargin = page.getWidth() * (1 - scaleFactor) / 2;
if (position < 0) {
page.setTranslationX(horzMargin - vertMargin / 2);
} else {
page.setTranslationX(-horzMargin + vertMargin / 2);
}
// Scale the page down (between MIN_SCALE and 1)
page.setScaleX(scaleFactor);
page.setScaleY(scaleFactor);
// Fade the page relative to its size.
page.setAlpha(MIN_ALPHA +
(scaleFactor - MIN_SCALE) /
(1 - MIN_SCALE) * (1 - MIN_ALPHA));
} else { // (1,+Infinity]
// Page is completely off-screen to the right.
page.setAlpha(0);
}
}
});
5.初始化ViewPager2:
在Activity或Fragment中初始化ViewPager2并设置适配器:
List<Bitmap> images = ...; // 初始化你的图片列表
GalleryAdapter adapter = new GalleryAdapter(images);
viewPager2.setAdapter(adapter);