有时候我们想动态的根据一个资源名获得到对应的资源id,就可以使用getResources().getIdentifier()方法来获取该id。然后再使用该id进行相关的操作。

1、Demo示例

下面用一个小Demo来讲解如何使用getResources().getIdentifier()方法来获取该id。

例如,新建一个Android项目,项目结构部分截图如下所示:

MainActivity代码如下:

package com.oyp.demo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView; public class MainActivity extends AppCompatActivity { private static final String TAG = MainActivity.class.getSimpleName(); private ImageView mImageView; private ImageView mipmapImageView; private TextView mTextView; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //获取布局文件资源的ID
int layoutId = getResources().getIdentifier("activity_main", "layout", getPackageName());
Log.d(TAG, "----> 获取到的图片资源 drawableId= " + layoutId); //获取图片资源的ID
mImageView = (ImageView) findViewById(R.id.imageView);
int drawableId = getResources().getIdentifier("oyp", "drawable", getPackageName());
mImageView.setImageResource(drawableId);
Log.d(TAG, "----> 获取到的图片资源 drawableId=" + drawableId); mipmapImageView = (ImageView) findViewById(R.id.mipmapImageView);
int mipmapId = getResources().getIdentifier("ic_launcher", "mipmap", getPackageName());
mipmapImageView.setImageResource(mipmapId);
Log.d(TAG, "----> 获取到的图片资源 mipmapId=" + mipmapId); //获取字符串资源
mTextView = (TextView) findViewById(R.id.textView);
int stringId = getResources().getIdentifier("author", "string", getPackageName());
mTextView.setText(stringId);
Log.d(TAG, "----> 获取到的字符串资源 stringId=" + stringId);
}
}

布局文件代码如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.oyp.demo.MainActivity"> <TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="@string/title" />
<ImageView
android:id="@+id/mipmapImageView"
android:layout_below="@id/title"
android:layout_marginTop="40dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"/> <ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" /> <TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/imageView"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dip" /> </RelativeLayout>

用到的strings.xml字符串资源代码如下:

<resources>

    <string name="app_name">Demo</string>
<string name="title">利用getIdentifier()方法获取资源ID</string>
<string name="author">欧阳鹏 http://blog.csdn.net/ouyang_peng</string> </resources>

运行该程序,运行效果如下所示:

打印出来的log为:

11-24 22:15:02.471 12023-12023/com.oyp.demo D/MainActivity: ----> 获取到的图片资源 drawableId= 2130968601
11-24 22:15:02.476 12023-12023/com.oyp.demo D/MainActivity: ----> 获取到的图片资源 drawableId=2130837579
11-24 22:15:02.477 12023-12023/com.oyp.demo D/MainActivity: ----> 获取到的图片资源 mipmapId=2130903040
11-24 22:15:02.477 12023-12023/com.oyp.demo D/MainActivity: ----> 获取到的字符串资源 stringId=2131099669

我们打开编译好后的 com.oyp.demo.R文件

首先来看看activity_main这个layout的id是不是和我们打印出来的一样是2130968601,如下图所示,在 com.oyp.demo.R文件中,activity_main的值确实是2130968601

部分代码如下所示:

public static final class layout {
...... public static final int abc_screen_simple = 2130968595;
public static final int abc_screen_simple_overlay_action_mode = 2130968596;
public static final int abc_screen_toolbar = 2130968597;
public static final int abc_search_dropdown_item_icons_2line = 2130968598;
public static final int abc_search_view = 2130968599;
public static final int abc_select_dialog_material = 2130968600;
public static final int activity_main = 2130968601;
public static final int notification_media_action = 2130968602;
public static final int notification_media_cancel_action = 2130968603;
public static final int notification_template_big_media = 2130968604;
public static final int notification_template_big_media_narrow = 2130968605; ...... public layout() {
}
}

drawable类型的图片 ic_launcher 的资源id 为 2130903040

 public static final class mipmap {
public static final int ic_launcher = 2130903040; public mipmap() {
}
}

drawable类型的图片 oyp 资源id为 2130837579

public static final class drawable {
...... public static final int abc_textfield_search_material = 2130837578;
public static final int notification_template_icon_bg = 2130837580;
public static final int oyp = 2130837579; public drawable() {
}
}

String类型的资源author id为 2131099669

public static final class string {

        ......

        public static final int app_name = 2131099668;
public static final int author = 2131099669;
public static final int status_bar_notification_info_overflow = 2131099667;
public static final int title = 2131099670; public string() {
}
}

可以发现打印出来的资源id和com.oyp.demo.R文件生成的资源id是一致的,因此使用getResources().getIdentifier()方法完全可以正确地获取资源的id。

2、getIdentifier()方法封装

点击查看getIdentifier()方法源代码如下所示:

/**
* 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.
*
* <p>Note: use of this function is discouraged. It is much more
* efficient to retrieve resources by identifier than by name.
*
* @param name The name of the desired resource.
* @param defType Optional default resource type to find, if "type/" is
* not included in the name. Can be null to require an
* explicit type.
* @param defPackage Optional default package to find, if "package:" is
* not included in the name. Can be null to require an
* explicit package.
*
* @return int The associated resource identifier. Returns 0 if no such
* resource was found. (0 is not a valid resource ID.)
*/
public int getIdentifier(String name, String defType, String defPackage) {
if (name == null) {
throw new NullPointerException("name is null");
}
try {
return Integer.parseInt(name);
} catch (Exception e) {
// Ignore
}
return mAssets.getResourceIdentifier(name, defType, defPackage);
}

第一个参数为资源ID名,第二个为资源属性的类型,第三个为包名。

下面是一个封装好的工具栏,可以直接用来获取资源id。

package com.oyp.demo;

import android.content.Context;

/**
* 工具类,可以通过资源名来获取资源id
* </p><br/><br/><br/>
* <a href = " http://blog.csdn.net/ouyang_peng "> 欧阳鹏博客</a>
*/
public class ResourceUtil { public static int getId(Context context, String resourceName) {
return getIdentifierByType(context, resourceName, "id");
} public static int getLayoutId(Context context, String resourceName) {
return getIdentifierByType(context, resourceName, "layout");
} public static int getStringId(Context context, String resourceName) {
return getIdentifierByType(context, resourceName, "string");
} public static int getDrawableId(Context context, String resourceName) {
return getIdentifierByType(context, resourceName, "drawable");
} public static int getMipmapId(Context context, String resourceName) {
return getIdentifierByType(context, resourceName, "mipmap");
} public static int getColorId(Context context, String resourceName) {
return getIdentifierByType(context, resourceName, "color");
} public static int getDimenId(Context context, String resourceName) {
return getIdentifierByType(context, resourceName, "dimen");
} public static int getAttrId(Context context, String resourceName) {
return getIdentifierByType(context, resourceName, "attr");
} public static int getStyleId(Context context, String resourceName) {
return getIdentifierByType(context, resourceName, "style");
} public static int getAnimId(Context context, String resourceName) {
return getIdentifierByType(context, resourceName, "anim");
} public static int getArrayId(Context context, String resourceName) {
return getIdentifierByType(context, resourceName, "array");
} public static int getIntegerId(Context context, String resourceName) {
return getIdentifierByType(context, resourceName, "integer");
} public static int getBoolId(Context context, String resourceName) {
return getIdentifierByType(context, resourceName, "bool");
} private static int getIdentifierByType(Context context, String resourceName, String defType) {
return context.getResources().getIdentifier(resourceName,
defType,
context.getPackageName());
}
}

将封装好的com.oyp.demo.ResourceUtil类应用到刚才的MainActivity中,代码如下:

package com.oyp.demo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView; public class MainActivity extends AppCompatActivity { private static final String TAG = MainActivity.class.getSimpleName(); private ImageView mImageView; private ImageView mipmapImageView; private TextView mTextView; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //获取布局文件资源的ID
// int layoutId = getResources().getIdentifier("activity_main", "layout", getPackageName());
int layoutId = ResourceUtil.getLayoutId(this, "activity_main");
Log.d(TAG, "----> 获取到的布局文件资源 drawableId= " + layoutId); //获取图片资源的ID
mImageView = (ImageView) findViewById(R.id.imageView);
// int drawableId = getResources().getIdentifier("oyp", "drawable", getPackageName());
int drawableId = ResourceUtil.getDrawableId(this, "oyp");
mImageView.setImageResource(drawableId);
Log.d(TAG, "----> 获取到的图片资源 drawableId=" + drawableId); mipmapImageView = (ImageView) findViewById(R.id.mipmapImageView);
// int mipmapId = getResources().getIdentifier("ic_launcher", "mipmap", getPackageName());
int mipmapId = ResourceUtil.getMipmapId(this, "ic_launcher");
mipmapImageView.setImageResource(mipmapId);
Log.d(TAG, "----> 获取到的图片资源 mipmapId=" + mipmapId); //获取字符串资源
mTextView = (TextView) findViewById(R.id.textView);
// int stringId = getResources().getIdentifier("author", "string", getPackageName());
int stringId = ResourceUtil.getStringId(this, "author");
mTextView.setText(stringId);
Log.d(TAG, "----> 获取到的字符串资源 stringId=" + stringId); int colorId = ResourceUtil.getColorId(this , "colorPrimary");
Log.d(TAG, "----> 获取到的颜色资源 colorId=" + colorId); int dimenId = ResourceUtil.getDimenId(this , "abc_dialog_min_width_major");
Log.d(TAG, "----> 获取到的颜色资源 dimenId=" + dimenId); int integerId = ResourceUtil.getIntegerId(this , "abc_config_activityDefaultDur");
Log.d(TAG, "----> 获取到的integer资源 integerId=" + integerId); int boolId = ResourceUtil.getBoolId(this , "abc_allow_stacked_button_bar");
Log.d(TAG, "----> 获取到的bool资源 boolId=" + boolId); int attrId = ResourceUtil.getAttrId(this , "actionBarDivider");
Log.d(TAG, "----> 获取到的attr资源 attrId=" + attrId); }
}

打印出来的Log日志为:

11-24 23:44:16.911 8543-8543/com.oyp.demo D/MainActivity: ----> 获取到的布局文件资源 drawableId= 2130968601
11-24 23:44:16.916 8543-8543/com.oyp.demo D/MainActivity: ----> 获取到的图片资源 drawableId=2130837579
11-24 23:44:16.918 8543-8543/com.oyp.demo D/MainActivity: ----> 获取到的图片资源 mipmapId=2130903040
11-24 23:44:16.918 8543-8543/com.oyp.demo D/MainActivity: ----> 获取到的字符串资源 stringId=2131099669
11-24 23:44:16.918 8543-8543/com.oyp.demo D/MainActivity: ----> 获取到的颜色资源 colorId=2131427347
11-24 23:44:16.918 8543-8543/com.oyp.demo D/MainActivity: ----> 获取到的颜色资源 dimenId=2131230730
11-24 23:44:16.918 8543-8543/com.oyp.demo D/MainActivity: ----> 获取到的integer资源 integerId=2131361793
11-24 23:44:16.918 8543-8543/com.oyp.demo D/MainActivity: ----> 获取到的bool资源 boolId=2131165184
11-24 23:44:16.918 8543-8543/com.oyp.demo D/MainActivity: ----> 获取到的attr资源 attrId=2130772027

作者:欧阳鹏 欢迎转载,与人分享是进步的源泉!

转载请保留原文地址:

http://blog.csdn.net/ouyang_peng/article/details/53328000

【我的Android进阶之旅】Android使用getIdentifier()方法根据资源名来获取资源id的更多相关文章

  1. 我的Android进阶之旅------>Android颜色值(#AARRGGBB)透明度百分比和十六进制对应关系以及计算方法

    我的Android进阶之旅-->Android颜色值(RGB)所支持的四种常见形式 透明度百分比和十六进制对应关系表格 透明度 十六进制 100% FF 99% FC 98% FA 97% F7 ...

  2. 我的Android进阶之旅------>Java字符串格式化方法String.format()格式化float型时小数点变成逗号问题

    今天接到一个波兰的客户说有个APP在英文状态下一切运行正常,但是当系统语言切换到波兰语言的时候,程序奔溃了.好吧,又是我来维护. 好吧,先把系统语言切换到波兰语,切换到波兰语的方法查看文章 我的And ...

  3. 我的Android进阶之旅------>Android中查看应用签名信息

    一.查看自己的证书签名信息 如上一篇文章<我的Android进阶之旅------>Android中制作和查看自定义的Debug版本Android签名证书>地址:http://blog ...

  4. 我的Android进阶之旅------>Android利用温度传感器实现带动画效果的电子温度计

    要想实现带动画效果的电子温度计,需要以下几个知识点: 1.温度传感器相关知识. 2.ScaleAnimation动画相关知识,来进行水印刻度的缩放效果. 3.android:layout_weight ...

  5. 我的Android进阶之旅------>Android实现用Android手机控制PC端的关机和重启的功能(三)Android客户端功能实现

    我的Android进阶之旅------>Android实现用Android手机控制PC端的关机和重启的功能(一)PC服务器端(地址:http://blog.csdn.net/ouyang_pen ...

  6. 我的Android进阶之旅------> Android为TextView组件中显示的文本添加背景色

    通过上一篇文章 我的Android进阶之旅------> Android在TextView中显示图片方法 (地址:http://blog.csdn.net/ouyang_peng/article ...

  7. 我的Android进阶之旅------> Android在TextView中显示图片方法

    面试题:请说出Android SDK支持哪些方式显示富文本信息(不同颜色.大小.并包含图像的文本信息),并简要说明实现方法. 答案:Android SDK支持如下显示富文本信息的方式. 1.使用Tex ...

  8. 我的Android进阶之旅------>Android疯狂连连看游戏的实现之实现游戏逻辑(五)

    在上一篇<我的Android进阶之旅------>Android疯狂连连看游戏的实现之加载界面图片和实现游戏Activity(四)>中提到的两个类: GameConf:负责管理游戏的 ...

  9. 我的Android进阶之旅------>Android疯狂连连看游戏的实现之加载界面图片和实现游戏Activity(四)

    正如在<我的Android进阶之旅------>Android疯狂连连看游戏的实现之状态数据模型(三)>一文中看到的,在AbstractBoard的代码中,当程序需要创建N个Piec ...

  10. 我的Android进阶之旅------>Android疯狂连连看游戏的实现之状态数据模型(三)

    对于游戏玩家而言,游戏界面上看到的"元素"千变万化:但是对于游戏开发者而言,游戏界面上的元素在底层都是一些数据,不同数据所绘制的图片有所差异而已.因此建立游戏的状态数据模型是实现游 ...

随机推荐

  1. numpy.ravel()/numpy.flatten()/numpy.squeeze()

    numpy.ravel(a, order='C') Return a flattened array numpy.chararray.flatten(order='C') Return a copy ...

  2. tp框架事务处理

    当我们需要同时对多个表进行操作的时候就有必要进行事务处理,首先你的数据库和数据表必须满足事务处理,即表引擎为InnoDB 下面为一个demo //事务:表必须是innodb    //删除主表$mod ...

  3. struts-tiles学习笔记

    网上搜了一些,稀里糊涂的,要么是代码不全,要么是版本不对,还是去struts官网大概学习了一下 http://struts.apache.org/development/1.x/struts-tile ...

  4. python练习题4-判断日期是一年的第几天

    题目:输入某年某月某日,判断这一天是这一年的第几天? 程序分析:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于2时需考虑多加一天: 程序源代码: ...

  5. PHP——上传文件

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  6. hdu6069 Counting Divisors 晒区间素数

    /** 题目:hdu6069 Counting Divisors 链接:http://acm.hdu.edu.cn/showproblem.php?pid=6069 题意:求[l,r]内所有数的k次方 ...

  7. 常用的AJAX框架

    你有没有想过设计你的网站像桌面应用程序?幸运的是,使用AJAX,我们可以做到这一点.通过使用AJAX,当我们只想更新网站的一部分(如天气信息或新闻面板)时,我们无需刷新整个页面.这使我们的网络应用看起 ...

  8. centos7 mysql 5.7 官网下载tar安装

    https://dev.mysql.com/downloads/mysql/5.7.html#downloads 下载好上传到服务器,解压后以此安装 libs,client,server三个rpm r ...

  9. EasyUI项目学习

    介绍easyui的使用,主要包括以下组件 布局面板 - layout 可伸缩面板 - accordion 选项卡 - tabs 控制面板 - panel 窗口 - window 对话框 - dialo ...

  10. XStream的基本使用

    先准备两个bean public class Book { private int bookId; private String bookName; private String bookCode; ...