【我的Android进阶之旅】Android使用getIdentifier()方法根据资源名来获取资源id
有时候我们想动态的根据一个资源名获得到对应的资源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的更多相关文章
- 我的Android进阶之旅------>Android颜色值(#AARRGGBB)透明度百分比和十六进制对应关系以及计算方法
		我的Android进阶之旅-->Android颜色值(RGB)所支持的四种常见形式 透明度百分比和十六进制对应关系表格 透明度 十六进制 100% FF 99% FC 98% FA 97% F7 ... 
- 我的Android进阶之旅------>Java字符串格式化方法String.format()格式化float型时小数点变成逗号问题
		今天接到一个波兰的客户说有个APP在英文状态下一切运行正常,但是当系统语言切换到波兰语言的时候,程序奔溃了.好吧,又是我来维护. 好吧,先把系统语言切换到波兰语,切换到波兰语的方法查看文章 我的And ... 
- 我的Android进阶之旅------>Android中查看应用签名信息
		一.查看自己的证书签名信息 如上一篇文章<我的Android进阶之旅------>Android中制作和查看自定义的Debug版本Android签名证书>地址:http://blog ... 
- 我的Android进阶之旅------>Android利用温度传感器实现带动画效果的电子温度计
		要想实现带动画效果的电子温度计,需要以下几个知识点: 1.温度传感器相关知识. 2.ScaleAnimation动画相关知识,来进行水印刻度的缩放效果. 3.android:layout_weight ... 
- 我的Android进阶之旅------>Android实现用Android手机控制PC端的关机和重启的功能(三)Android客户端功能实现
		我的Android进阶之旅------>Android实现用Android手机控制PC端的关机和重启的功能(一)PC服务器端(地址:http://blog.csdn.net/ouyang_pen ... 
- 我的Android进阶之旅------> Android为TextView组件中显示的文本添加背景色
		通过上一篇文章 我的Android进阶之旅------> Android在TextView中显示图片方法 (地址:http://blog.csdn.net/ouyang_peng/article ... 
- 我的Android进阶之旅------> Android在TextView中显示图片方法
		面试题:请说出Android SDK支持哪些方式显示富文本信息(不同颜色.大小.并包含图像的文本信息),并简要说明实现方法. 答案:Android SDK支持如下显示富文本信息的方式. 1.使用Tex ... 
- 我的Android进阶之旅------>Android疯狂连连看游戏的实现之实现游戏逻辑(五)
		在上一篇<我的Android进阶之旅------>Android疯狂连连看游戏的实现之加载界面图片和实现游戏Activity(四)>中提到的两个类: GameConf:负责管理游戏的 ... 
- 我的Android进阶之旅------>Android疯狂连连看游戏的实现之加载界面图片和实现游戏Activity(四)
		正如在<我的Android进阶之旅------>Android疯狂连连看游戏的实现之状态数据模型(三)>一文中看到的,在AbstractBoard的代码中,当程序需要创建N个Piec ... 
- 我的Android进阶之旅------>Android疯狂连连看游戏的实现之状态数据模型(三)
		对于游戏玩家而言,游戏界面上看到的"元素"千变万化:但是对于游戏开发者而言,游戏界面上的元素在底层都是一些数据,不同数据所绘制的图片有所差异而已.因此建立游戏的状态数据模型是实现游 ... 
随机推荐
- nyoj 740 “炫舞家“ST
			“炫舞家“ST 时间限制:3000 ms | 内存限制:65535 KB 难度:3 描述 ST是一个酷爱炫舞的玩家.TA很喜欢玩QQ炫舞,因此TA也爱屋及乌的喜欢玩跳舞机(Dance Dance ... 
- Github 创建新分支
			一.clone Repository clone Github 上的Repository,如下: git clone git@github.com:FBing/design-patterns.git ... 
- Oracle Explain plan 使用总结
			Oracle Explain plan使用总结 写多了SQL语句,伴随着数据量的海增,总会遇到性能的问题.在Oracle领域一个不好的习惯,一旦遇到性能问题就推给DBA来做.长期如此,反而对DB ... 
- Nginx中修改php.ini的上传设置upload_max_filesize的值
			普遍的网络越来越快,以前小家子气的2M上传限制慢慢变得不合时宜了.最近就把2M的限制直接提升到了20M...代码层面很快就修改好了,没什么可说的.但是上线的话还得修改一下服务器的配置.服务器是Ngin ... 
- liunx下安装tomcat7.0.82
			1.apache-tomcat-liunx-7.0.82下载地址: http://download.csdn.net/download/yichen01010/10019116 2.下载后解压即可 c ... 
- pom打包参数选择
			pom.xml配置 <profiles> <profile> <id>dev</id> <properties> <token> ... 
- 运行jsp需要安装_______Web服务器。
			运行jsp需要安装_______Web服务器. A.Apache B.tomcat C.WebLogic D.IIS 解答:BC Apache是PHP程序运行的服务器,IIS是.net程序运行的服务器 ... 
- java 理解java的三大特性之继承
			继承定义了类如何相互关联,共享特性.对于若干个相同或者相识的类,我们可以抽象出他们共有的行为或者属相并将其定义成一个父类或者超类,然后用这些类继承该父类,他们不仅可以拥有父类的属性.方法还可以定义自己 ... 
- python3----练习题(装饰器)
			装饰器本质上是一个函数,该函数用来处理其他函数,它可以让其他函数在不需要修改代码的前提下增加额外的功能,装饰器的返回值也是一个函数对象.也就是说装饰器的作用就是为已经存在的对象添加额外的功能. 当使用 ... 
- python3----生成器generator(yield)
			# 列表推导式a = [i for i in range(100) if not(i % 2) and (i % 3)]print(a)# 字典推导式b = {i: i % 2 == 0 for i ... 
