引言
在Android开发中相信大家都会遇到修改用户头像的问题,用户信息常常包含用户头像,一般流程为:默认头像——>用户修改(拍照/相册选择)——>保存头像图片。
本期我们就来实现调用系统相机来进行相册选择图片的功能。话不多说,请先看效果图,再看代码。
传送门
效果预览
用法
第一步:布局文件
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".show.Case24"
tools:ignore="MissingConstraints">
<Button
android:id="@+id/choose_photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="从相册中选择照片"
android:textSize="20sp"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="@+id/picture"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:src="@drawable/meizi2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
第二步:添加权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
第三步:在activity中实现
public class Case24 extends AppCompatActivity {
public static final int CHOOSE_PHOTO = 2;
ImageView picture;
String imagePath = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_case24);
Button btnChoosePhoto = (Button) findViewById(R.id.choose_photo);
picture = (ImageView) findViewById(R.id.picture);
btnChoosePhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
requestPermissino();
}
});
picture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
requestPermissino();
}
});
}
private void requestPermissino() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}else {
openAlbum();
}
}
private void openAlbum(){
Intent intent = new Intent("android.intent.action.GET_CONTENT");
intent.setType("image/*");
startActivityForResult(intent,CHOOSE_PHOTO); //打开相册
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case 1:
if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
openAlbum();
}else {
Toast.makeText(this,"你拒绝了该权限",Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case CHOOSE_PHOTO:
if(resultCode == RESULT_OK){
//判断手机系统版本号
if(Build.VERSION.SDK_INT>=19){
//4.4及以上系统使用这个方法处理图片
handleImageOnKitKat(data);
}
}
break;
default:
break;
}
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void handleImageOnKitKat(Intent data){
Uri uri = data.getData();
if(DocumentsContract.isDocumentUri(this,uri)){
//如果是document类型的Uri,则通过document id处理
String docId = DocumentsContract.getDocumentId(uri);
if("com.android.providers.media.documents".equals(uri.getAuthority())){
String id = docId.split(":")[1]; //解析出数字格式的id
String selection = MediaStore.Images.Media._ID+"="+id;
imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
}else if("com.android.providers.downloads.documents".equals(uri.getAuthority())){
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public downloads"),Long.valueOf(docId));
imagePath = getImagePath(contentUri,null);
}
}else if("content".equalsIgnoreCase(uri.getScheme())){
//如果是file类型的Uri,直接获取图片路径即可
imagePath = getImagePath(uri,null);
}else if("file".equalsIgnoreCase(uri.getScheme())){
//如果是file类型的Uri,直接获取图片路径即可
imagePath = uri.getPath();
}
displayImage(imagePath); //根据图片路径显示图片
}
//将选择的图片Uri转换为路径
private String getImagePath(Uri uri,String selection){
String path = null;
//通过Uri和selection来获取真实的图片路径
Cursor cursor = getContentResolver().query(uri,null,selection,null,null);
if(cursor!= null){
if(cursor.moveToFirst()){
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
cursor.close();
}
return path;
}
//展示图片
private void displayImage(String imagePath){
if(imagePath!=null && !imagePath.equals("")){
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
picture.setImageBitmap(bitmap);
//存储上次选择的图片路径,用以再次打开app设置图片
SharedPreferences sp = getSharedPreferences("sp_img",MODE_PRIVATE); //创建xml文件存储数据,name:创建的xml文件名
SharedPreferences.Editor editor = sp.edit(); //获取edit()
editor.putString("imgPath",imagePath);
editor.apply();
}else {
Toast.makeText(this,"获取图片失败",Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onResume() {
super.onResume();
//设置再次app时显示的图片
SharedPreferences sp = getSharedPreferences("sp_img", MODE_PRIVATE);
//取出上次存储的图片路径设置此次的图片展示
String beforeImagePath = sp.getString("imgPath", null);
displayImage(beforeImagePath);
}
}
大功告成!
效果图
千夜零一:"之前总是看各种博客学习东西,现在我想用博客记录下我的学习脚步,好东西也需要分享,索取和给予是相互的。以后会尽量日更的!目标完成1001篇博客哈哈。”
如果觉得对你有所帮助,请不要吝啬你的点赞,有问题也可以在下方评论区留言哦,关注我一起学习吧~