当前位置: 代码迷 >> Android >> android透过字符串标识加载资源
  详细解决方案

android透过字符串标识加载资源

热度:95   发布时间:2016-05-01 16:50:50.0
android通过字符串标识加载资源
int i=  getResources().getIdentifier("icon", "drawable", getPackageName()) ;
if(i>0)
   {Log.i("aa","aa");}
else
   {Log.i("vbv","aa");}

或者

int resID = getResources().getIdentifier("org.loveandroid.androidtest:drawable/icon",null,null);

int resID = getResources().getIdentifier("icon", "drawable", "org.anddev.android.testproject");




Resources resources = context.getResources();
int indentify = resources.getIdentifier(context.getPackageName()+":drawable/"+iconName, null, null);
if(indentify>0){
icon = resources.getDrawable(indentify);
}

以下是getIdentifier的API文档,可见最重要的是第一个参数,格式是:包名 + : + 资源文件夹名 + / +资源名
如果找到了,返回资源Id,如果找不到,返回0 public int getIdentifier (String name, String defType, String defPackage)
Since: API Level 1Return a resource identifier for the given resource name. A fully qualified resource name is of the form "package:type/entry". The first two components (package and type) are optional if defType and defPackage, respectively, are specified here.

Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.
Parameters
name The name of the desired resource.
defType Optional default resource type to find, if "type/" is not included in the name. Can be null to require an explicit type.
defPackage Optional default package to find, if "package:" is not included in the name. Can be null to require an explicit package.
Returns
int The associated resource identifier. Returns 0 if no such resource was found. (0 is not a valid resource ID.) 
  相关解决方案