【问题标题】:How to get list of image with R.Drawable如何使用 R.Drawable 获取图像列表
【发布时间】:2012-11-07 09:30:12
【问题描述】:

为了创建一个磁贴管理系统,我的 res/drawable 目录中有一组图像。如何动态加载该资源?

点赞:F_16.0_0_112.jpg. ("F_"+zoom"+"._"+XCoord+"_"+YCoord".jpg")

有没有像 getDrawable(String) 这样的函数?

【问题讨论】:

  • 你可以,但是你可以把你的drawable放在一个levellistdrawable中,或者放在一个资源数组中。 (或在资产文件夹中)

标签: android image url drawable


【解决方案1】:

您可以通过以下方式使用其名称获取可绘制对象:

int id = getResources().getIdentifier("name_of_resource", "id", getPackageName());

【讨论】:

    【解决方案2】:

    您可以使用反射来获得它(不要忘记导入 java.lang.reflect.Field)

    /**
     * For example calling <code>getDrawableId("ic_launcher")</code> will return the same value as <code>R.drawable.ic_launcher;</code> 
     * 
     * @param name the name of the field
     * @return the drawable id
     */
    public int getDrawableId(String name) {
        Class<?> c = R.drawable.class;
        Field f = null;
        int id = 0;
    
        try {
            f = R.drawable.class.getField(name);
            id = f.getInt(null);
        } catch (NoSuchFieldException e) {
            Log.i("Reflection", "Missing drawable " + name);
        } catch (IllegalAccessException e) {
            Log.i("Reflection", "Illegal access to field " + name);
        }
    
        return id;
    }
    

    【讨论】:

      【解决方案3】:

      不,为此使用 android assets 文件夹。

      更多详情请查看here

      【讨论】:

        【解决方案4】:

        很遗憾,您不能按名称加载资源。 id 是生成的 R 类中的变量。在java中,你不能建立动态变量名。

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-04-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多