简单实现打开系统相册选择一张图片并显示在UI上,适用与个人主页头像的切换。
1. 添加存储权限。AndroidManifest.xml里添加读取内存的权限。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
2. 布局。布局内容比较交单,一个Button用来打开相册;一个ImageView用来接收从相册选择的图片。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btn_open_gallery"
android:layout_width="150dp"
android:layout_height="75dp"
android:layout_centerHorizontal="true"
android:text="打开相册"
android:textSize="20sp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:layout_below="@+id/btn_open_gallery"/>
</RelativeLayout>
3. 动态申请权限。Google 在 Android 6.0 开始引入了权限申请机制,除了再AndroidManifest.xml里申请静态权限,还需要在代码里动态申请。
/**
* 申请动态权限
*/
private void applyPermission() {
//检测权限
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// 如果没有权限,则申请需要的权限
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}else {
// 已经申请了权限
openGallery();
}
}
4. 申请权限的回调。
/**
* 用户选择是否开启权限操作后的回调;TODO 同意/拒绝
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 用户同样授权
openGallery();
}else {
// 用户拒绝授权
Toast.makeText(this, "你拒绝使用存储权限!", Toast.LENGTH_SHORT).show();
Log.d("HL", "你拒绝使用存储权限!");
}
}
}
5. 打开相册。
/**
* 打开相册
*/
private void openGallery() {
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI , "image/*");
startActivityForResult(intent, OPEN_GALLERY_REQUEST_CODE);
}
6. 结果回调。用户选择了一张图片,接收返回的结果并在ImageView里显示。、文章来源:https://www.toymoban.com/news/detail-776486.html
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == OPEN_GALLERY_REQUEST_CODE) { // 检测请求码
if (resultCode == Activity.RESULT_OK && data != null) {
try {
InputStream inputStream = getContentResolver().openInputStream(data.getData());
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
// TODO 把获取到的图片放到ImageView上
mImg.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
完整Demo文章来源地址https://www.toymoban.com/news/detail-776486.html
package com.example.opengallery;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST_CODE = 0;
private static final int OPEN_GALLERY_REQUEST_CODE = 1;
private static final int TAKE_PHOTO_REQUEST_CODE = 2;
private Button mOpenGallery;
private ImageView mImg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mOpenGallery = findViewById(R.id.btn_open_gallery);
mImg = findViewById(R.id.img);
//打开相册
mOpenGallery.setOnClickListener(v -> {
applyPermission();
});
}
/**
* 申请动态权限
*/
private void applyPermission() {
//检测权限
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// 如果没有权限,则申请需要的权限
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}else {
// 已经申请了权限
openGallery();
}
}
/**
* 用户选择是否开启权限操作后的回调;TODO 同意/拒绝
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 用户同样授权
openGallery();
}else {
// 用户拒绝授权
Toast.makeText(this, "你拒绝使用存储权限!", Toast.LENGTH_SHORT).show();
Log.d("HL", "你拒绝使用存储权限!");
}
}
}
/**
* 打开相册
*/
private void openGallery() {
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI , "image/*");
startActivityForResult(intent, OPEN_GALLERY_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == OPEN_GALLERY_REQUEST_CODE) { // 检测请求码
if (resultCode == Activity.RESULT_OK && data != null) {
try {
InputStream inputStream = getContentResolver().openInputStream(data.getData());
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
// TODO 把获取到的图片放到ImageView上
mImg.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
到了这里,关于Android---打开相册选择图片的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!