android studio读取相册
时间: 2023-09-12 14:09:59 浏览: 76
要在Android Studio中读取相册,你可以使用以下步骤:
1. 在AndroidManifest.xml文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
```
2. 在布局文件中添加一个按钮,并在相应的Activity中为按钮添加一个点击事件:
```xml
<Button
android:id="@+id/btn_open_gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="打开相册"/>
```
```java
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE = 1;
private Button btnOpenGallery;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOpenGallery = findViewById(R.id.btn_open_gallery);
btnOpenGallery.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 imageUri = data.getData();
// Do something with the image Uri
}
}
}
```
3. 在Activity中的onActivityResult()方法中获取选中的图片的Uri,并进行相应的处理。
阅读全文