4

嘿,我已经找了一段时间了。以下代码从 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));

    }


}
4

1 回答 1

5

用户唯一选择的是图片的路径。因此,如果您将路径保存到 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();
}

在选择图像中使用您当前的代码开始挑选活动,然后在 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));

    }
于 2013-09-07T00:23:06.540 回答