那要怎么修改呢
时间: 2024-02-23 15:02:17 浏览: 47
你可以将 `ImageAdapter` 类修改为继承自 `RecyclerView.Adapter`,然后实现 `getItemCount()`、`onCreateViewHolder()` 和 `onBindViewHolder()` 方法。具体实现如下:
```java
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ViewHolder> {
private List<ImageBean> mImages;
public ImageAdapter(List<ImageBean> images) {
mImages = images;
}
@Override
public int getItemCount() {
return mImages.size();
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.poster_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
ImageBean imageBean = mImages.get(position);
Glide.with(holder.itemView)
.load(imageBean.getUrl())
.transform(new CenterCrop(), new RoundedCornersTransformation(10, 0, RoundedCornersTransformation.CornerType.TOP))
.into(holder.imageView);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(holder.itemView.getContext(), "被点击了", Toast.LENGTH_SHORT).show();
}
});
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public ViewHolder(View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.iv_poster_image);
}
}
}
```
然后,在使用 `ViewPager2` 的地方,创建一个 `ImageAdapter` 对象,并将其传入 `ViewPager2` 的 `setAdapter()` 方法中:
```java
List<ImageBean> images = // 获取数据集合
ViewPager2 viewPager2 = findViewById(R.id.viewPager2);
viewPager2.setAdapter(new ImageAdapter(images));
```
阅读全文