引言
??在Android開發(fā)中相信大家都會遇到修改用戶頭像的問題仅乓,用戶信息常常包含用戶頭像,一般流程為:默認(rèn)頭像——>用戶修改(拍照/相冊選擇)——>保存頭像圖片蓬戚。
??本期我們就來實(shí)現(xiàn)調(diào)用系統(tǒng)相機(jī)來進(jìn)行相冊選擇圖片的功能夸楣。話不多說,請先看效果圖子漩,再看代碼裕偿。
傳送門
??兄弟篇:Android調(diào)用相機(jī)實(shí)現(xiàn)拍照功能
效果預(yù)覽
調(diào)用系統(tǒng)相冊.gif
用法
第一步:布局文件
<?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>
第二步:添加權(quán)限
<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中實(shí)現(xiàn)
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,"你拒絕了該權(quán)限",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){
//判斷手機(jī)系統(tǒng)版本號
if(Build.VERSION.SDK_INT>=19){
//4.4及以上系統(tǒng)使用這個(gè)方法處理圖片
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]; //解析出數(shù)字格式的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); //根據(jù)圖片路徑顯示圖片
}
//將選擇的圖片Uri轉(zhuǎn)換為路徑
private String getImagePath(Uri uri,String selection){
String path = null;
//通過Uri和selection來獲取真實(shí)的圖片路徑
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設(shè)置圖片
SharedPreferences sp = getSharedPreferences("sp_img",MODE_PRIVATE); //創(chuàng)建xml文件存儲數(shù)據(jù)旭绒,name:創(chuàng)建的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();
//設(shè)置再次app時(shí)顯示的圖片
SharedPreferences sp = getSharedPreferences("sp_img", MODE_PRIVATE);
//取出上次存儲的圖片路徑設(shè)置此次的圖片展示
String beforeImagePath = sp.getString("imgPath", null);
displayImage(beforeImagePath);
}
}
大功告成鸟妙!
效果圖
相冊選圖.jpeg
千夜零一:"之前總是看各種博客學(xué)習(xí)東西焦人,現(xiàn)在我想用博客記錄下我的學(xué)習(xí)腳步,好東西也需要分享重父,索取和給予是相互的花椭。以后會盡量日更的!目標(biāo)完成1001篇博客哈哈房午】罅桑”
??如果覺得對你有所幫助,請不要吝嗇你的點(diǎn)贊郭厌,有問題也可以在下方評論區(qū)留言哦袋倔,關(guān)注我一起學(xué)習(xí)吧~