Android 程序开发:如何选择手机相册图片
在 Android 编写程序时,选择手机相册图片可以通过以下步骤实现:
- 在
AndroidManifest.xml文件中添加读取外部存储器的权限:
<uses-permission android:name='android.permission.READ_EXTERNAL_STORAGE'/>
- 在布局文件中添加一个
ImageView控件用于显示选中的图片:
<ImageView
android:id='@+id/imageView'
android:layout_width='match_parent'
android:layout_height='wrap_content'
android:src='@drawable/default_image'/>
- 在
Activity中添加一个按钮控件用于触发选取图片的操作,并设置按钮的点击事件监听器:
Button chooseImageButton = findViewById(R.id.choose_image_button);
chooseImageButton.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, PICK_IMAGE_REQUEST);
}
});
其中,PICK_IMAGE_REQUEST 是一个自定义的常量,用于标识选取图片的请求。
- 在
Activity中重写onActivityResult()方法,处理选取图片的结果:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri imageUri = data.getData();
imageView.setImageURI(imageUri);
}
}
其中,imageUri 是选取的图片的 URI,通过 setImageURI() 方法将图片显示在 ImageView 控件中。
以上就是在安卓编写程序时选择手机相册图片的方法。
原文地址: https://www.cveoy.top/t/topic/ooui 著作权归作者所有。请勿转载和采集!