简体   繁体   中英

Android get Resource Identifier for a resource that doesn't belong to my app

This is how we get a resource identifier for a drawable that belongs to our app

int resID = getResources().getIdentifier("resourceName",
"drawable", "myPackageName");

But how do we do it when the drawable is not ours?
1. It belongs to android
2. It belongs to another app (I'm guessing that this is done by just using the other app's package name)

This is my solution and it works for me..Assuming that the iconResName is in the form of: packageName+":drawable/"+drawableName; I get the resources Id with the following function i wrote. And then we can use this resId to get the drawable.

public static int getResIdFromResEntryName(String iconResName,Context con){
  try{
    String packageName = iconResName.split(":")[0]; 
    Context otherAppContext = con.createPackageContext(packageName,Context.CONTEXT_INCLUDE_CODE|Context.CONTEXT_IGNORE_SECURITY);
    Resources resources = otherAppContext.getResources();
    int resId = resources.getIdentifier(iconResName, null, null);
    return resId;
  }catch(Exception e){return 0;}    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM