资源 Id简介:

我们平时获取资源是通过 findViewById 方法进行的,比如我们常在onCreate方法中使用这样的语句:

btnChecked=(ImageView)findViewById(R.id.imgCheck);

findViewById是我们获取layout中各种View 对象比如按钮、标签、ListView和ImageView的便利方法。顾名思义,它需要一个int参数:资源id。

资源id非常有用。Android回自动为每个位于res目录下的资源分配id,包括各种图片文件、xml文中的”@+id”对象。res的子目录几乎总是固定的,比如每次都能见到的:drawable-xxxx、layout、values,以及不常见的:anim、xml、row、color。

Android会为res目录下的所有资源分配id,其主要的分配原则是:

drawable中的图片文件总是每个文件一个资源id。

Xml文件中每个使用android:id=”@+id/xxx”的view都会被分配一个未用的资源id。

--------------------------------------------------------------------------------------------------------------------------------------------

使用getIdentifier()获取资源Id:

函数原型:

int  getIdentifier(String name, String defType, String defPackage)

Return 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.)

1> 方式一

Resources resources = context.getResources();int indentify = resources.getIdentifier(org.loveandroid.androidtest:drawable/icon”,null,null);if(indentify>0){icon = resources.getDrawable(indentify);
第一个参数格式是:包名 + : + 资源文件夹名 + / +资源名;是这种格式 然后其他的可以为null

2> 方式二

Resources resources = context.getResources(); int indentify= getResources().getIdentifier("icon", "drawable", "org.anddev.android.testproject");

第一个参数为ID名,第二个为资源属性是ID["id"]或者是Drawable["drawable"],第三个为包名。


附加:

获取资源中的其他资源:

    1.要是想获得string可以这样写:

    getResources().getIdentifier("name", "string", packdgeName);

    2.要是想获得array中的数组,可以这样写:

    getResources().getIdentifier("name", "array", packdgeName);



更多相关文章

  1. Android音频播放
  2. Android(安卓)Studio老是提示重启ADB解决!
  3. Android(安卓)ProGuard代码混淆
  4. Android(安卓)OTA 升级之四:进入根文件系统
  5. Android(安卓)Wear Eclipse开发环境搭建
  6. android studio 删除、导入jar包
  7. [Android]res下面layout增加子文件夹
  8. Ubuntu 下不能识别android设备的解决方法
  9. eclipse 上调试android的自带应用方法 一

随机推荐

  1. SQL获取第一条记录的方法(sqlserver、ora
  2. SqlServer异常处理常用步骤
  3. SQL语句执行顺序详解
  4. SQL SERVER 2014 安装图解教程(含SQL SERV
  5. SQLite之Autoincrement关键字(自动递增)
  6. master数据库损坏的解决办法有哪些
  7. 如何把sqlserver数据迁移到mysql数据库及
  8. 修改SQL-SERVER数据库表结构的SQL命令附s
  9. sql server中随机函数NewID()和Rand()
  10. 使用NotePad++录制宏功能如何快速将sql搜