有时候我们想动态的根据一个资源名获得到对应的资源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. ubuntu下记录所有用户的登录和操作日志

    一般我们可以用history命令来查看当前用户的操作记录,但是这个命令不能记录是所有用户登录操作的,也不能记录详细的操作时间,且不完整:所以误操作而造成重要的数据丢失,就很难查到是谁操作导致的. 在这 ...

  2. Java的ThreadContext类加载器的实现

    疑惑 以前在看源码的时候,总是会遇到框架里的代码使用Thread.currentThread.getContextClassLoader()获取当前线程的Context类加载器,通过这个Context ...

  3. Android App常规测试内容

    转自:https://mp.weixin.qq.com/s?__biz=MzU0NjcyNDg3Mw==&mid=2247484053&idx=1&sn=116fe8c7eed ...

  4. js将秒数换算成时分秒

    转载自:http://jingyan.baidu.com/article/375c8e19a0413925f2a229d2.html <script language="javascr ...

  5. uboot中断功能实现

    uboot中实现irq中断(uboot version2015.04)1.实验目的:实现GPIO_2的外部中断 2.实验步骤:a.GPIO_2(GPIO1_IO02)为中断源, 首先需要设置这个pad ...

  6. 栈类Stack

    Stack类是Vector类的子类.它向用户提供了堆栈这种高级的数据结构.栈的基本特性就是先进后出.即先放入栈中的元素将后被推出.Stack类中提供了相应方法完成栈的有关操作. 基本方法: publi ...

  7. smartJS 0.1 API 讲解 - FlowController

    本篇介绍0.1版中最后一个特性,FlowController:同时也对第一版总结一下,因为近两年全部都是在搞前端,都是做一些js框架类的东西,也做了不少有意思的功能,做smartjs对我来说一个是对自 ...

  8. 虚拟机(VMware Workstation)安装Ubuntu简易安装

    1.安装虚拟机 这里我安装的是:VMware Workstation v12.1.0 官方简体中文版 地址:http://www.3987.com/xiazai/1/12/37116.html#dow ...

  9. shell学习三十八天----运行顺序和eval

    运行顺序和eval shell从标准输入或脚本中读取的每一行称为管道,它包括了一个或多个命令,这些命令被一个或多个管道字符(|)隔开. 其实嗨哟非常多特殊符号可用来切割单个的命令:分号(;),管道(| ...

  10. asp.net页面触发事件panel滚动条高度不变的实现方法

    asp.net页面按钮点击触发事件后panel滚动条非自动回到顶端,每次都要往下拉一下,关于这个问题的解决方法如下 此文是为解决asp.net页面按钮点击触发事件后panel滚动条非自动回到顶端的解决 ...