Android

Android JetPack学习总结(二十二)

完善PhotoGallery,保存图片

根据欲加载的图片高度设置ImageView的高度:

imageView.getLayoutParams().height=getItem(position).getPhotoHeight();

增加显示了一些新的数据。

image 4
图片保存

首先创建一个Drawable资源,为一个按压之后状态会发生改变的按钮。

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/ic_baseline_saved_24"/>
<item android:drawable="@drawable/ic_baseline_save_24"/>
</selector>

申请写存储器权限:

首先要先在manifests中声明权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

在点击保存按钮时动态申请权限

saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

if (Build.VERSION.SDK_INT<29&& ContextCompat.checkSelfPermission(requireContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
Toast.makeText(getContext(),"onclick",Toast.LENGTH_LONG).show();
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_WRITE);
}
}
});

API 29以上的不需要动态申请权限了。

保存图片:

    private void savePhoto(){
PagerPhotoViewHolder holder=(PagerPhotoViewHolder) ((RecyclerView)viewPager2.getChildAt(0)).findViewHolderForAdapterPosition(viewPager2.getCurrentItem());
Bitmap bitmap=((BitmapDrawable)((ImageView)holder.itemView.findViewById(R.id.pagerPhoto)).getDrawable()).getBitmap();

Uri saveUri=requireContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,new ContentValues());
if (saveUri == null) {
Toast.makeText(requireContext(),"存储失败",Toast.LENGTH_LONG).show();
return;
}else {
OutputStream outputStream = null;
try {
outputStream=requireContext().getContentResolver().openOutputStream(saveUri);
bitmap.compress(Bitmap.CompressFormat.JPEG,90,outputStream);
Toast.makeText(requireContext(),"存储成功",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
Toast.makeText(requireContext(),"存储失败",Toast.LENGTH_LONG).show();
e.printStackTrace();
}finally {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//低版本
// if (MediaStore.Images.Media.insertImage(requireContext().getContentResolver(),bitmap,"","")==null){
// Toast.makeText(requireContext(),"存储失败",Toast.LENGTH_LONG).show();
// }else {
// Toast.makeText(requireContext(),"存储成功",Toast.LENGTH_LONG).show();
// }

}

首先得获取保存图片的imageView,然后将其图片内容(drawable)转化为BItmap。注意这里有一个bug,当图片没加载出来时,点击保存按钮会将展位图保存,会报错:vectorDrawable can not cast to Bitmap。

发表评论