要实现像相册一样的效果,需要使用RecyclerView来展示图片。首先,在layout布局文件中定义一个RecyclerView和一个ImageView。RecyclerView的布局使用GridLayoutManager,ImageView用来放置选中的图片预览。接下来,创建一个适配器来绑定数据和视图。在适配器中,将数据绑定到ImageView,并为RecyclerView的每个item设置点击事件。当item被点击时,使用Glide加载选中的图片,并将其显示在ImageView中。
以下是示例代码:
public class PhotoAdapter extends RecyclerView.Adapter {
private List photos;
private Context context;
private ImageView previewImage;
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView image;
public ViewHolder(View itemView) {
super(itemView);
image = itemView.findViewById(R.id.imageView);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Glide.with(context).load(photos.get(getAdapterPosition())).into(previewImage);
previewImage.setVisibility(View.VISIBLE);
}
}
public PhotoAdapter(List photos, Context context, ImageView previewImage) {
this.photos = photos;
this.context = context;
this.previewImage = previewImage;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.photo_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Glide.with(context).load(photos.get(position)).into(holder.image);
}
@Override
public int getItemCount() {
return photos.size();
}
}