Android中实现根据资源名获取资源ID

接触过Android开发的同学们都知道在Android中访问程序资源基本都是通过资源ID来访问。这样开发起来很简单,并且可以不去考虑各种分辨率,语言等不同资源显式指定。

痛点

但是,有时候也会有一些问题,比如我们根据服务器端的值取图片,但是服务器端绝对不会返回给我们的是资源id,最多是一种和文件名相关联的值,操作资源少的时候,可以维护一个容器进行值与资源ID的映射,但是多的话,就需要另想办法了。

便捷的方法

在这种情况下,使用文件名来得到资源ID显得事半功倍。 通过调用Resources的getIdentifier可以很轻松地得到资源ID。 几个简单的示例:

复制代码 代码如下:
Resources res = getResources();
final String packageName = getPackageName();
int imageResId = res.getIdentifier("ic_launcher", "drawable", packageName);
int imageResIdByAnotherForm = res.getIdentifier(packageName + ":drawable/ic_launcher", null, null);
 
int musicResId = res.getIdentifier("test", "raw", packageName);
     
int notFoundResId = res.getIdentifier("activity_main", "drawable", packageName);

Log.i(LOGTAG, "testGetResourceIds imageResId = " + imageResId
              + ";imageResIdByAnotherForm = " + imageResIdByAnotherForm
              + ";musicResId=" + musicResId
              + ";notFoundResId =" + notFoundResId);

运行结果

复制代码 代码如下:
I/MainActivity( 4537): testGetResourceIds imageResId = 2130837504;imageResIdByAnotherForm = 2130837504;musicResId=2130968576;notFoundResId =0

看一看API

直接API

1.这个方法用来使用资源名来获取资源ID
2.完整的资源名为package:type/entry,如果资源名这个参数有完整地指定,后面的defType和defPackage可以省略。
3.defType和defPackage省略时,需要将其设置成null
4.注意这个方法不提倡,因为直接通过资源ID访问资源会更加效率高
5.如果资源没有找到,返回0,在Android资源ID中0不是合法的资源ID。

复制代码 代码如下:
**
     * 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) {
        try {
            return Integer.parseInt(name);
        } catch (Exception e) {
            // Ignore
        }
        return mAssets.getResourceIdentifier(name, defType, defPackage);
    }

间接API

实际上上述API调用的是AssetManager.class中的native方法。

复制代码 代码如下:
/**
     * Retrieve the resource identifier for the given resource name.
     */
    /*package*/ native final int getResourceIdentifier(String type,
                                                       String name,
                                                       String defPackage);

时间: 2024-07-31 22:53:56

Android中实现根据资源名获取资源ID的相关文章

Android中实现根据资源名获取资源ID_Android

接触过Android开发的同学们都知道在Android中访问程序资源基本都是通过资源ID来访问.这样开发起来很简单,并且可以不去考虑各种分辨率,语言等不同资源显式指定. 痛点 但是,有时候也会有一些问题,比如我们根据服务器端的值取图片,但是服务器端绝对不会返回给我们的是资源id,最多是一种和文件名相关联的值,操作资源少的时候,可以维护一个容器进行值与资源ID的映射,但是多的话,就需要另想办法了. 便捷的方法 在这种情况下,使用文件名来得到资源ID显得事半功倍. 通过调用Resources的get

Android中引用其他程序的文本资源超简单方法

在Android中引用其他程序的文本资源并不是很常见,但是有时候还是很是有需要的,通常引用的多半是系统的程序的文本资源. 下面以一个超简单的例子,来展示以下如何实现. 复制代码 代码如下: public void testUseAndroidString() { Context context = getContext();     Resources res = null;     try {         //I want to use the clear_activities strin

Android中Java根据文件头获取文件类型的方法_Android

本文实例讲述了Android中Java根据文件头获取文件类型的方法.分享给大家供大家参考,具体如下: 前面讲过Android系统内部的MediaFile类来获取文件类型的办法,这个类主要是根据文件的扩展名来判断,其准确性不是很好.具体可查看Android系统使用MediaFile类判断音频文件类型.其实,获取文件类型最好的办法便是根据文件头信息来判断.下面贴出相关代码: public class FileType { public static final HashMap<String, Str

Python中如何根据包名获取Module对象?

问题描述 Python中如何根据包名获取Module对象? 知道一个包名,现在想获取对应的Module对象,Python中怎么实现?比如path = 'attnedence.models.EmployeeIP', 如何得到这个对象?

Android利用资源名称获取其ID(一)---&amp;gt;getIdentifier()

MainActivity如下: package cc.wy; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; /** * Demo描述: * 利用getIdentifier()方法获取资源ID * * 方法描述: * getIdentifier

Android利用资源名称获取其ID(二)---&amp;gt;反射

MainActivity如下: package cn.testreflect; import java.lang.reflect.Field; import android.os.Bundle; import android.widget.ImageView; import android.app.Activity; /** * Demo描述: * 依据图片的名字,通过反射获取其在drawable中的ID * 在根据此ID显示图片 */ public class MainActivity ext

解析android中系统日期时间的获取_Android

复制代码 代码如下: import    java.text.SimpleDateFormat;     SimpleDateFormat    formatter    =   new    SimpleDateFormat    ("yyyy年MM月dd日    HH:mm:ss     ");     Date    curDate    =   new    Date(System.currentTimeMillis());//获取当前时间     String    str 

动态获取资源ID-用getIdentifier()获取资源Id

做项目过程中遇到一个问题,从数据库里读取图片名称,然后调用图片.直接用R.drawable.?无法调用.查了好多地方最后找到了个方法,分享给大家,希望有帮助. 主要由两种方法,个人建议第二种. 1. 不把图片放在res/drawable下,而是存放在src某个package中(如:com.drawable.resource),这种情况下的调用方法为: String path = "com/drawable/resource/imageName.png"; InputStream is

android中知道图片name时获取图片的简单方法_Android

1. 图片放在sdcard中, 复制代码 代码如下: Bitmap imageBitmap = BitmapFactory.decodeFile(path)  (path 是图片的路径,跟目录是/sdcard) 2. 图片在项目的res文件夹下面 复制代码 代码如下: //得到application对象 ApplicationInfo appInfo = getApplicationInfo(); //得到该图片的id(name 是该图片的名字,"drawable" 是该图片存放的目录