android – 保存从图库中选取的图像以备将来使用
作者:互联网
嘿,我一直在寻找一段时间.以下代码从android库中选择图像并在imageView中显示.但事实上,只要应用程序关闭并重新启动,就必须再次选择.我想知道如何编辑以下内容以在imageView中保存图像.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
解决方法:
用户唯一挑选的是图片的路径.因此,如果您将路径保存到SharedPreferences,那么每次启动应用程序时,您都可以使用现有代码,但只需更改获取路径的位置:
String picturePath = PreferenceManager.getDefaultSharedPreferences(this).getString("picturePath", "");
if(!picturePath.equals(""))
{
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
编辑:
这是一个可以在OnCreate中使用的完整方法:
String picturePath = PreferenceManager.getDefaultSharedPreferences(this).getString("picturePath", "");
if(!picturePath.equals(""))
{
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
else {
selectImage();
}
在select image中使用当前代码开始挑选活动,然后在onActivityResult中使用:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
PreferenceManager.getDefaultSharedPreferences(this).edit().putString("picturePath", picturePath).commit();
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
标签:android-gallery,android,gallery 来源: https://codeday.me/bug/20190831/1776558.html