10

我想将Drawable转换为int,然后反之亦然。基本上我想将Arraylist对象保存到sharedPrefrence。为此,我实施了Gson到 Srtring 的转换方法。如果我在这里使用Drawable而不是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;
}

这是将自定义对象的 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);
4

3 回答 3

6

Int -> 可绘制:

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

可绘制-> Int:

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

一旦你设置你的R.drawable.app1to 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());

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

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

ApplicationInfo applicationInfo = mContext.getPackageManager().getApplicationInfo(apps.get(position).getPname(),1);
int icon= applicationInfo.icon;
于 2015-12-27T17:23:18.647 回答
1

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

                   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));

                    }
于 2016-11-30T06:41:30.540 回答
0

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

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

我传入了packageName:

val drawable = context.getPackageManager().getApplicationIcon(packageName)这是字符串,可以很容易地传递。

于 2020-05-13T11:41:53.077 回答