zoukankan      html  css  js  c++  java
  • Android 获取有规律资源Id解决方案

    在多个有规律的资源ID获取的时候,可以使用getIdentifier方法来获取,来获取。

    用到场景:工具类打成.jar包的时候,有时候会需要引用到res中的资源,这时候不能将资源一起打包,只能通过反射机制动态的获取资源.

    public class Resources int getIdentifier (String name, String defType, String defPackage)
    Return a resource identifier for the given resource name.
    param defType:"layout","string","drawable","style","color","array"
    Parameters
    name The name of the desired resource.
    defType Optional default resource type to find, if "type/" is not included in the name. Can be null to require an explicit type.
    defPackage Optional default package to find, if "package:" is not included in the name. Can be null to require an explicit package.
    Returns
    • int The associated resource identifier. Returns 0 if no such resource was found. (0 is not a valid resource ID.)

    from: http://developer.android.com/reference/android/content/res/Resources.html

      

    public static int getDrawableId(Context paramContext, String paramString) { 
            return paramContext.getResources().getIdentifier(paramString, 
                    "drawable", paramContext.getPackageName()); 
        } 
         
    

     

    对于这个方法,官方不推荐:

    Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.

    更好的解决方案,是参照另外一篇博客的使用反射实现的。

    http://www.liaohuqiu.net/cn/posts/android-get-resource-id-by-string/

    示例代码:

    public static int getResId(String variableName, Class<?> c) {
        try {
            Field idField = c.getDeclaredField(variableName);
            return idField.getInt(idField);
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }
    

      

    使用:

    int id = ResourceMan.getResId("icon", R.drawable.class);
    

      

    这种效率据说比第一种高了4倍。

     

  • 相关阅读:
    C语言 汉诺塔问题
    指向函数的指针 linux中常见的函数指针应用及函数指针数组
    C语言 折半/二分法查找
    C语言 stdlib.h自带函数库:qsort()排序,简称"快排"
    几种排序算法的稳定性归纳
    C语言 归并排序
    c语言 堆排序 多函数处理法
    C语言 递归方法实现快速排序
    C语言 通过输出排序次数来比较希尔排序和插入排序的优劣
    c语言 希尔排序简化函数版
  • 原文地址:https://www.cnblogs.com/spring87/p/4855186.html
Copyright © 2011-2022 走看看