android+studio实现相册选择图片
时间: 2023-12-08 13:39:29 浏览: 162
以下是Android Studio实现相册选择图片的步骤:
1.在AndroidManifest.xml文件中添加读取外部存储器的权限:
```xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
```
2.在布局文件中添加一个ImageView用于显示选择的图片:
```xml
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:adjustViewBounds="true"
android:scaleType="centerCrop" />
```
3.在Activity中添加以下代码:
```java
private static final int REQUEST_CODE = 1;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
// 添加点击事件,打开相册
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_CODE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
Uri uri = data.getData();
imageView.setImageURI(uri);
}
}
```
4.运行程序,点击ImageView即可打开相册选择图片并显示在ImageView中。
阅读全文