具有一个类,该类引用String和drawable的资源值,我需要持久化该类并在将来加载它。我坚持使用GSON和共享的首选项。
问题是,我总是对我的应用程序的资源进行更改,持久化值的resourceID不再有效,因为应用程序中所有资源的资源ID都发生了变化。
如何避免这个问题?我需要坚持上那堂课。
这是我要保留的类的代码的最小示例:
public class SpaceshipUpdate {
private int nameResource;
private int imageResource;
public SpaceshipUpdate(int nameResource, int imageResource){
this.nameResource = nameResource;
this.imageResource = imageResource;
}
}
以及我如何创建该类的新实例:
SpaceshipUpdate u1 = new SpaceshipUpdate(R.string.laser1_title, R.drawable.shop_proton_laser);
谢谢
您可以将资源的名称(例如:“ laser1_title”)保留为字符串而不是R.string.laser1_title
版本,并使用此辅助函数(或类似的东西)来动态获取该资源。
它可能没有那么快,但是如果您没有很多资源,就不会注意到任何性能问题。
public static int has_resource_id(Context context,String name,String resource_type)
{
final int resourceId = context.getResources().getIdentifier(name, resource_type,
context.getApplicationContext().getPackageName());
return resourceId;
}