如何在Android中将Drawable转换为int,反之亦然

M.A*_*han 7 android drawable android-sharedpreferences

我想将Drawable转换为int然后反之亦然.基本上我想将Arraylist对象保存到sharedPrefrence中.为此我有实施Gson到Srtring转换方法.如果我在这里使用Drawable而不是int,那么Gson String转换需要很多时间.所以我想使用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()));
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

以下是将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);
Run Code Online (Sandbox Code Playgroud)

Kon*_*nov 6

整数 -> 可绘制:

Drawable icon = getResources().getDrawable(42, getTheme());

可绘制 -> 整数:

(我假设,您正在填充List<AppInfo> apps其图标已经在res/drawable您的应用程序文件夹中的应用程序)

一旦你设置了你R.drawable.app1ImageView,你也可以给它一个tagImageView后面识别资源:

    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());
Run Code Online (Sandbox Code Playgroud)

如果您的图标来自服务器 - 唯一的方法是将它们存储到磁盘,然后重新加载它们。(或者,更好的是,依靠已经存在的图像缓存解决方案,如picasso

UPD: 没有直接转换Drawable为 的方法int,但在这种特殊情况下,可以获取int, 而不是Drawablefrom PackageManager

ApplicationInfo applicationInfo = mContext.getPackageManager().getApplicationInfo(apps.get(position).getPname(),1);
int icon= applicationInfo.icon;
Run Code Online (Sandbox Code Playgroud)