How to convert Drawable to int and vice versa in Android

I want to convert Drawable to int , and then vice versa. Basically, I want to keep Arraylist in sharedPrefrence strong>. For this purpose, I implement Gson for the Srtring conversion method. If I use Drawable here instead of int , then converting the Gson String will take a lot of time. so I want to use int instead of 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())); 

Where is AppInfo here

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

Here is the source of converting ArrayList to a custom object in String so that I can save it in 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); 
+5
source share
2 answers

Int β†’ Drawable:

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

Drawable β†’ Int:

(I assume that you populate the List<AppInfo> apps application whose icons are already in the res/drawable your application)

Once you set R.drawable.app1 to ImageView , you can also specify a tag to identify the resource in ImageView later:

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

If your icons come from the server, the only way to save them to disk is then reload them. (or, better, rely on pre-existing image caching solutions like picasso )

UPD: There is no direct way to convert Drawable to int , but in this particular case, you can get int instead of Drawable from PackageManager :

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

Here's how we can extract the application icon and set it to view images.

  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)); } 
0
source

Source: https://habr.com/ru/post/1239298/


All Articles