我从上面修改了 Jens 的答案,因为正如评论中所述,name 永远不会为 null,而是抛出异常。
private boolean isResourceIdInPackage(String packageName, int resId){
if(packageName == null || resId == 0){
return false;
}
Resources res = null;
if(packageName.equals(getPackageName())){
res = getResources();
}else{
try{
res = getPackageManager().getResourcesForApplication(packageName);
}catch(PackageManager.NameNotFoundException e){
Log.w(TAG, packageName + "does not contain " + resId + " ... " + e.getMessage());
}
}
if(res == null){
return false;
}
return isResourceIdInResources(res, resId);
}
private boolean isResourceIdInResources(Resources res, int resId){
try{
getResources().getResourceName(resId);
//Didn't catch so id is in res
return true;
}catch (Resources.NotFoundException e){
return false;
}
}