Android点击按钮在相册选择图片在页面中显示
时间: 2024-02-28 18:57:22 浏览: 20
好的,您可以参考以下代码实现:
1. 在你的布局文件中添加一个Button和一个ImageView(用于显示选中的图片):
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/select_image_button"
android:text="选择图片"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/selected_image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
```
2. 在你的Activity中,添加以下代码:
```
private static final int SELECT_IMAGE_REQUEST = 1; // 请求码,用于标识选择图片的请求
private ImageView mSelectedImageView; // 用于显示选中的图片
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button selectImageButton = findViewById(R.id.select_image_button);
mSelectedImageView = findViewById(R.id.selected_image_view);
selectImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 创建Intent,用于打开相册
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "选择图片"), SELECT_IMAGE_REQUEST);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_IMAGE_REQUEST && resultCode == RESULT_OK) {
// 获取选中的图片的URI
Uri imageUri = data.getData();
// 将选中的图片显示在ImageView中
mSelectedImageView.setImageURI(imageUri);
}
}
```
当用户点击选择图片的按钮时,会打开相册,用户选择一张图片后,会回调onActivityResult方法,你可以在这个方法中获取选中的图片的URI,然后将其显示在ImageView中。