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

How to convert Drawable into int and vice versa in Android

我想把Drawable转换成int然后副versa.Basically我想保存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()));

这里的 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;
}

这是将自定义对象的 ArrayList 转换为字符串的来源,以便我可以将其保存到 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:

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

Drawable -> Int:

(我假设,您正在使用应用程序填充 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 and then re-load them. (or, better, rely on the already existing image-caching solutions like picasso)

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

ApplicationInfo applicationInfo = mContext.getPackageManager().getApplicationInfo(apps.get(position).getPname(),1);
int icon= applicationInfo.icon;

这就是我们获取应用程序图标并将其设置为图像视图的方法。

                   applicationInfo=mContext.getPackageManager().getApplicationInfo(apps.get(position).getPname(),PackageManager.GET_META_DATA);
                   int icon= applicationInfo.icon;
                   Rsources resources=mContext.getPackageManager().getResourcesForApplication(applicationInfo);

                 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        holder.itemIcon.setImageDrawable(resources.getDrawable(icon,null));
                    }else
                    {
                         holder.itemIcon.setImageDrawable(resources.getDrawable(icon));

                    }

唯一对我有用的解决方案是在@KonstantinLoginov 的 chat 中,而不是使用:

val drawable = context.getPackageManager().getApplicationIcon(applicationInfo),

我传入的包名:

val drawable = context.getPackageManager().getApplicationIcon(packageName) 是字符串,可以轻松传递。