博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【我的Android进阶之旅】Android使用getIdentifier()方法根据资源名来获取资源id
阅读量:6628 次
发布时间:2019-06-25

本文共 11662 字,大约阅读时间需要 38 分钟。

有时候我们想动态的根据一个资源名获得到对应的资源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); }}

布局文件代码如下:

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

Demo
利用getIdentifier()方法获取资源ID
欧阳鹏 http://blog.csdn.net/ouyang_peng

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

这里写图片描述

打印出来的log为:

11-24 22:15:02.471 12023-12023/com.oyp.demo D/MainActivity: ----> 获取到的图片资源 drawableId= 213096860111-24 22:15:02.476 12023-12023/com.oyp.demo D/MainActivity: ----> 获取到的图片资源 drawableId=213083757911-24 22:15:02.477 12023-12023/com.oyp.demo D/MainActivity: ----> 获取到的图片资源 mipmapId=213090304011-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.     *      * 

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 * 

* 欧阳鹏博客 */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= 213096860111-24 23:44:16.916 8543-8543/com.oyp.demo D/MainActivity: ----> 获取到的图片资源 drawableId=213083757911-24 23:44:16.918 8543-8543/com.oyp.demo D/MainActivity: ----> 获取到的图片资源 mipmapId=213090304011-24 23:44:16.918 8543-8543/com.oyp.demo D/MainActivity: ----> 获取到的字符串资源 stringId=213109966911-24 23:44:16.918 8543-8543/com.oyp.demo D/MainActivity: ----> 获取到的颜色资源 colorId=213142734711-24 23:44:16.918 8543-8543/com.oyp.demo D/MainActivity: ----> 获取到的颜色资源 dimenId=213123073011-24 23:44:16.918 8543-8543/com.oyp.demo D/MainActivity: ----> 获取到的integer资源 integerId=213136179311-24 23:44:16.918 8543-8543/com.oyp.demo D/MainActivity: ----> 获取到的bool资源 boolId=213116518411-24 23:44:16.918 8543-8543/com.oyp.demo D/MainActivity: ----> 获取到的attr资源 attrId=2130772027

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

转载请保留原文地址:

这里写图片描述

你可能感兴趣的文章
查询指定库中所有表
查看>>
黄聪:用php判断当前用户访问网站是否为手机登录
查看>>
Flash AS3 Loader的一些总结
查看>>
.net(vs2010)调试技巧
查看>>
45个纯 CSS 实现的精美边框效果【附在线演示和源码】【下篇】
查看>>
js的逻辑 OR 运算符- ||
查看>>
[SQL Server]一次执行资料夹内的.sql 指令码
查看>>
【计算机视觉】粒子滤波跟踪
查看>>
hadoop集群扩展
查看>>
操作系统诊断
查看>>
[Compose] 19. Leapfrogging types with Traversable
查看>>
Tomcat version 7.0 only supports J2EE 1.2, 1.3, 1.4, and Java EE 5 and 6 Web modules
查看>>
2015年度新增开源软件排名TOP100
查看>>
设计模式 之 原型
查看>>
BZOJ 2456: mode(新生必做的水题)
查看>>
View State
查看>>
自旋锁spinlock解析
查看>>
【java.lang.UnsupportedClassVersionError】版本不一致出错
查看>>
JVM Debugger Memory View for IntelliJ IDEA
查看>>
LINUX下GDB反汇编和调试
查看>>