You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何保存ImageView设置?实现选中图片重启APP后持久化显示

How to Persist Selected Image Across App Restarts

Hey there! I see you want your selected image to stay in the ImageView even after restarting the app—let's get that working. The key here is to save the selected image's URI (instead of the full Bitmap, which is too bulky) using SharedPreferences, then load it back when the app starts up. Here's how to adjust your code:

Step 1: Add Constants for SharedPreferences

First, define some constants at the top of your Activity to keep things organized:

private static final String PREFS_NAME = "ImagePreferenceStorage";
private static final String KEY_SELECTED_IMAGE_URI = "saved_image_uri";
private static final int REQUEST_CODE = 1; // Make sure this is defined in your Activity too!

Step 2: Save the Image URI When Selected

Update your onActivityResult method to save the selected URI to SharedPreferences right after setting the image:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null) {
        Uri imageUri = data.getData();
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
            background2.setImageBitmap(bitmap);
            
            // Save the URI to SharedPreferences
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
            prefs.edit().putString(KEY_SELECTED_IMAGE_URI, imageUri.toString()).apply();
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Step 3: Restore the Image When the App Starts

Add code to your onCreate method to load the saved URI (if it exists) and display the image when the Activity launches:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_activity_layout); // Replace with your actual layout ID
    
    // Initialize your views first
    background2 = findViewById(R.id.your_imageview_id); // Replace with your ImageView ID
    button31 = findViewById(R.id.your_button_id); // Replace with your Button ID
    
    // Restore the saved image
    SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
    String savedUriString = prefs.getString(KEY_SELECTED_IMAGE_URI, null);
    
    if (savedUriString != null) {
        Uri savedImageUri = Uri.parse(savedUriString);
        try {
            Bitmap restoredBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), savedImageUri);
            background2.setImageBitmap(restoredBitmap);
        } catch (IOException e) {
            e.printStackTrace();
            // If the image can't be loaded (e.g., it was deleted), clear the saved URI
            prefs.edit().remove(KEY_SELECTED_IMAGE_URI).apply();
        }
    }
    
    // Your existing button click listener
    button31.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), REQUEST_CODE);
        }
    });
}

Important Notes

  • Why save the URI instead of Bitmap? Bitmaps take up a lot of memory, and SharedPreferences isn't designed to store large data. Saving the URI is lightweight and lets you reload the image from the media library whenever needed.
  • Permissions: For Android versions older than API 29 (Android 10), you'll need to add the READ_EXTERNAL_STORAGE permission to your AndroidManifest.xml and request it dynamically at runtime.
  • Handling missing images: If the user deletes the selected image from their device, loading it will fail. The code above catches that exception and clears the saved URI so the app doesn't keep trying to load a missing image.

内容的提问来源于stack exchange,提问作者jackal52

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:59:26