2012-06-04 92 views
2

我正在开发一个Android应用程序,其中一个页面上有一个imageView,onLongClick它从图像A更改为图像B.但是,当它们离开页面时,imageView会返回图像A.如何保存状态(即时猜测它在onpause,stop和destroy上完成),以便它保存ImageView的当前图像src,并在下一次访问和创建页面时加载它。我从来没有在Android中完成数据保存..在动态更改src后保存Android图像状态

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

回答

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

+0

嗨Krylez,如果应用程序完全关闭或者他们击中后退按钮的活动。这仍会检索数据吗?我的意思是,当然如果我把电话onDestroy/onStop等或保存instinstancestate丢失应用程序关闭时的数据 – karlstackoverflow

+0

关闭应用程序时,该包会丢失。它只存在于内存中,所以当Android OS关闭你的应用程序时,它永远消失了。即使您的应用程序关闭,SharedPreferences也会继续存在。 – Krylez

+0

谢谢。我想我需要使用SharedPreferences。 – karlstackoverflow