ImageView 多张相片 代码
时间: 2023-09-12 12:07:06 浏览: 207
以下是一个使用 `RecyclerView` 显示多张图片的示例代码:
1. 在 XML 中添加 `RecyclerView`:
```xml
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
```
2. 创建一个 `ImageAdapter` 类来绑定数据和视图:
```java
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ViewHolder> {
private List<Integer> mImages;
public ImageAdapter(List<Integer> images) {
mImages = images;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_image, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
int imageResId = mImages.get(position);
holder.imageView.setImageResource(imageResId);
}
@Override
public int getItemCount() {
return mImages.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
ViewHolder(@NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
}
}
}
```
3. 创建 `item_image.xml` 布局文件:
```xml
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="centerCrop" />
```
4. 在 Activity 中设置 `RecyclerView` 和 `ImageAdapter`:
```java
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private ImageAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
List<Integer> images = new ArrayList<>();
images.add(R.drawable.image1);
images.add(R.drawable.image2);
images.add(R.drawable.image3);
mAdapter = new ImageAdapter(images);
mRecyclerView.setAdapter(mAdapter);
}
}
```
注意,上面的代码中,`R.drawable.image1`、`R.drawable.image2`、`R.drawable.image3` 都是指定的图片资源的 ID,需要在项目中添加这些图片资源。
阅读全文