سؤال

I am developing an Android Application, where I have an imageView on a page and onLongClick it changes from Image A to Image B. However, when they leave the page the imageView goes back to Image A. How can I save the state (im guessing its done onpause, stop and destroy) so that it saves the current image src of the ImageView and load it up next time the page is accessed and created. I have never done data saving in Android..

Any simple data saving tutorial/example would be greatly appreciated.

هل كانت مفيدة؟

المحلول

Something along these lines should help you out:

// Use a static tag so you're never debugging typos
private static final String IMAGE_RESOURCE = "image-resource";
private int image;
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    // if there's no bundle, this is the first time; use default resource
    if (savedInstanceState == null) {
        image = R.drawable.default;
    } else {
        // if there is a bundle, use the saved image resource (if one is there)
        image = savedInstanceState.getInt(IMAGE_RESOURCE, R.drawable.default);
    }
}

@Override
public void onSaveInstanceState(Bundle outState) {
    // Make sure you save the current image resource 
    outState.putInt(IMAGE_RESOURCE, image);
    super.onSaveInstanceState(outState);
}

Make sure you set the image variable to the proper resource at the same time you change it in your click listener.

If you're looking to remember the state longer than this, look into SharedPreferences.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top