2

我正在开发一个Android应用程序,我在页面上有一个imageView,onLongClick它从Image A变为Image B。但是,当他们离开页面时,imageView又回到Image A。我怎样才能保存状态(我猜它完成了onpause,stop和destroy),以便它保存ImageView的当前图像src并在下次访问和创建页面时加载它。我从来没有在Android中保存过数据..

任何简单的数据保存教程/示例将不胜感激。

4

1 回答 1

4

这些方面的东西应该可以帮助你:

// 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);
}

确保在单击侦听器中更改图像变量的同时将其设置为正确的资源。

如果您想记住比这更长的状态,请查看SharedPreferences

于 2012-06-04T03:31:55.663 回答