我想将 Drawable 转换为 int ,然后反之亦然。基本上我想将 Arraylist 对象保存为 sharedPrefrence 。为此,我实现了 Gson 到Srtring转换方法。如果我在此处使用可绘制的而不是 int ,则Gson字符串转换会花费很多时间。所以我想使用int而不是Drawable。
private List<AppInfo> apps = null;
public void setIcon(int icon) {
this.icon = icon;
}
apps.get(position).setIcon(mContext.getResources().getDrawable(apps.get(position).getIcon()));
这里的AppInfo在哪里
public AppInfo(String appname, String pname, String versionName, int versionCode, int icon, int color) {
this.appname = appname;
this.pname = pname;
this.versionName = versionName;
this.versionCode = versionCode;
this.icon = icon;
this.color = color;
}
这是将Custom对象的ArrayList转换为String的源,因此我可以将其保存到SharedPrefrence。
Gson gson = new Gson();
apps.get(number).setColor(picker.getColor());
String JsonAppsdata = gson.toJson(apps);
System.out.println("Storing="+JsonAppsdata);
utility.StoreData(getApplicationContext(), JsonAppsdata);
最佳答案
Int->可绘制:Drawable icon = getResources().getDrawable(42, getTheme());
可绘制->整数:
(我假设您正在用应用程序的List<AppInfo> apps
填充图标,这些图标的图标已经在您应用程序的res/drawable
文件夹中)
将R.drawable.app1
设置为ImageView
后,您还可以为其指定一个tag
,以便以后在ImageView
中标识资源:
ImageView appIcon1ImageView = (ImageView)findViewById(R.id.app_icon_1);
appIcon1ImageView.setImageDrawable(getDrawable(R.drawable.app1));
appIcon1ImageView.setTag(R.drawable.app1);
......
// Once you need to identify which resource is in ImageView
int drawableId = Integer.parseInt(appIcon1ImageView.getTag().toString());
如果您的图标来自服务器-唯一的方法是to store them to disk,然后重新加载它们。 (或者更好的是,依赖于已经存在的图像缓存解决方案,例如picasso)
UPD:
没有直接的方法可以将
Drawable
转换为int
,但是在这种特殊情况下,可以从int
中获取Drawable
,而不是PackageManager
:ApplicationInfo applicationInfo = mContext.getPackageManager().getApplicationInfo(apps.get(position).getPname(),1);
int icon= applicationInfo.icon;