0

0

Android应用中通过字符串名称动态加载Drawable资源教程

花韻仙語

花韻仙語

发布时间:2025-12-05 21:39:43

|

1009人浏览过

|

来源于php中文网

原创

Android应用中通过字符串名称动态加载Drawable资源教程

android开发中,将drawable资源id直接存储在外部数据(如json)中会导致运行时错误,因为这些id在不同编译版本中不稳定。本教程将详细介绍如何通过在json中存储drawable资源的字符串名称,并在运行时使用 `getresources().getidentifier()` 方法动态获取正确的资源id,从而解决此问题,确保应用能够灵活、稳定地加载图片资源。

理解问题:Drawable资源ID的不稳定性

在Android应用开发中,资源(如Drawable、String、Layout等)在编译时会被分配一个唯一的整数ID,这些ID存储在 R.java 文件中。例如,R.drawable.tomato 会对应一个类似 0x7f0800a3 的整数值。然而,这些ID并不是固定不变的。每次应用重新编译时,或者在不同的构建环境中,同一个资源的ID都可能发生变化。

当我们将这些整数ID序列化到外部数据(如JSON文件)中,并在运行时尝试使用它们时,就可能遇到问题。如果应用版本更新或重新编译,JSON中存储的旧ID可能不再对应正确的资源,从而导致 Resources$NotFoundException 运行时错误,提示“Invalid ID”。

以下是一个典型的场景,展示了问题发生的环境:

Recipe.java 数据类

package me.eyrim.foodrecords2;

import com.google.gson.annotations.SerializedName;

public class Recipe {
    @SerializedName("recipe_name")
    private String recipeName;
    @SerializedName("recipe_desc")
    private String recipeDesc;
    @SerializedName("ingredients")
    private Ingredient[] ingredients;
    @SerializedName("recipe_id")
    private String recipeId;

    // Getter methods...
    public String getRecipeName() { return this.recipeName; }
    public String getRecipeDesc() { return this.recipeDesc; }
    public Ingredient[] getIngredients() { return this.ingredients; }
    public String getRecipeId() { return this.recipeId; }
}

Ingredient.java 数据类(原始设计)

package me.eyrim.foodrecords2;

import com.google.gson.annotations.SerializedName;

public class Ingredient {
    @SerializedName("ingredient_name")
    private String ingredientName;
    @SerializedName("ingredient_drawable_tag")
    private int ingredientDrawableTag; // 问题所在:存储了整数ID

    // Getter methods...
    public String getIngredientName() { return this.ingredientName; }
    public int getIngredientDrawableTag() { return this.ingredientDrawableTag; }
}

JSON数据示例(原始设计)

{
    "recipe_name": "My test recipe 1 updated",
    "recipe_id": "0",
    "recipe_desc": "this is a test desc for my test recipe 1",
    "ingredients": [{
            "ingredient_name": "Tomato",
            "ingredient_drawable_tag": 700003 // 存储了整数ID
        },
        {
            "ingredient_name": "Pepper",
            "ingredient_drawable_tag": 700002 // 存储了整数ID
        }
    ]
}

IngredientRecyclerViewAdapter.java(原始实现)

TemPolor
TemPolor

AI音乐生成器,一键创作免版税音乐

下载
package me.eyrim.foodrecords2.recipeviewactivity;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import me.eyrim.foodrecords2.Ingredient;
import me.eyrim.foodrecords2.R;

public class IngredientRecyclerViewAdapter extends RecyclerView.Adapter<IngredientRecyclerViewAdapter.IngredientViewHolder> {
    private final Ingredient[] ingredients;
    // private final Context context; // 原始代码中缺少对Context的成员变量引用

    public IngredientRecyclerViewAdapter(Ingredient[] ingredients, Context context) {
        this.ingredients = ingredients;
        // this.context = context; // 如果要使用Context,需要在此处保存
    }

    @NonNull
    @Override
    public IngredientViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.ingredient_row, parent, false);
        return new IngredientViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull IngredientViewHolder holder, int position) {
        // 尝试直接使用JSON中读取的整数ID,导致运行时错误
        holder.imageView.setImageResource(this.ingredients[position].getIngredientDrawableTag());
    }

    @Override
    public int getItemCount() {
        return this.ingredients.length;
    }

    public class IngredientViewHolder extends RecyclerView.ViewHolder {
        private final ImageView imageView;

        public IngredientViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.ingredient_image);
        }
    }
}

当 onBindViewHolder 方法尝试使用 ingredients[position].getIngredientDrawableTag() 返回的整数ID设置 ImageView 的图片时,如果该ID不再有效,就会抛出 android.content.res.Resources$NotFoundException 异常。

解决方案:通过字符串名称动态加载Drawable

为了解决Drawable资源ID不稳定的问题,我们应该在外部数据中存储资源的名称(字符串),而不是其整数ID。在运行时,我们可以利用Android Context 提供的 getResources().getIdentifier() 方法,根据资源的名称动态查找并获取其当前的整数ID。

这个方法接受三个参数:

  1. name:资源的字符串名称(例如 "tomato")。
  2. defType:资源的类型(例如 "drawable", "string", "layout" 等)。
  3. defPackage:资源所属的包名(通常是应用的包名,可以通过 context.getPackageName() 获取)。

步骤一:修改数据类 (Ingredient.java)

将 ingredientDrawableTag 字段的类型从 int 修改为 String,以存储Drawable资源的名称。

package me.eyrim.foodrecords2;

import com.google.gson.annotations.SerializedName;

public class Ingredient {
    @SerializedName("ingredient_name")
    private String ingredientName;
    @SerializedName("ingredient_drawable_tag")
    private String ingredientDrawableTag; // 修改为String类型

    public String getIngredientName() {
        return this.ingredientName;
    }

    public String getIngredientDrawableTag() {
        return this.ingredientDrawableTag;
    }
}

步骤二:更新JSON数据结构

将JSON中的 ingredient_drawable_tag 值从整数ID修改为对应的Drawable资源名称(不带 R.drawable. 前缀)。

{
    "recipe_name": "My test recipe 1 updated",
    "recipe_id": "0",
    "recipe_desc": "this is a test desc for my test recipe 1",
    "ingredients": [{
            "ingredient_name": "Tomato",
            "ingredient_drawable_tag": "tomato" // 修改为字符串名称
        },
        {
            "ingredient_name": "Pepper",
            "ingredient_drawable_tag": "pepper" // 修改为字符串名称
        }
    ]
}

步骤三:修改RecyclerView Adapter (IngredientRecyclerViewAdapter.java)

在 IngredientRecyclerViewAdapter 中,我们需要保存 Context 实例,以便在 onBindViewHolder 方法中使用它来调用 getResources().getIdentifier()。

package me.eyrim.foodrecords2.recipeviewactivity;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import me.eyrim.foodrecords2.Ingredient;
import me.eyrim.foodrecords2.R;

public class IngredientRecyclerViewAdapter extends RecyclerView.Adapter<IngredientRecyclerViewAdapter.IngredientViewHolder> {
    private final Ingredient[] ingredients;
    private final Context context; // 新增:保存Context引用

    public IngredientRecyclerViewAdapter(Ingredient[] ingredients, Context context) {
        this.ingredients = ingredients;
        this.context = context; // 初始化Context
    }

    @NonNull
    @Override
    public IngredientViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.ingredient_row, parent, false);
        return new IngredientViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull IngredientViewHolder holder, int position) {
        // 获取Drawable的字符串名称
        String drawableName = this.ingredients[position].getIngredientDrawableTag();

        // 使用getIdentifier动态获取资源ID
        int drawableId = context.getResources().getIdentifier(
            drawableName,      // 资源的名称,例如 "tomato"
            "drawable",        // 资源的类型,这里是 "drawable"
            context.getPackageName() // 应用的包名
        );

        // 检查是否成功找到资源ID,并设置图片
        if (drawableId != 0) {
            holder.imageView.setImageResource(drawableId);
        } else {
            // 如果资源未找到,可以设置一个默认的占位符图片
            holder.imageView.setImageResource(R.drawable.default_placeholder); // 假设有一个默认图片
            // 也可以在此处记录错误日志
            System.err.println("Drawable resource not found for name: " + drawableName);
        }
    }

    @Override
    public int getItemCount() {
        return this.ingredients.length;
    }

    public class IngredientViewHolder extends RecyclerView.ViewHolder {
        private final ImageView imageView;

        public IngredientViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.ingredient_image);
        }
    }
}

注意事项与最佳实践

  1. Context的传递与保存: getIdentifier() 方法需要一个 Context 实例来访问应用的资源。在 RecyclerView.Adapter 中,通常在构造函数中接收 Context 并将其保存为成员变量。
  2. 资源名称的一致性: 确保JSON中存储的字符串名称与 res/drawable 目录下的实际Drawable文件名(不含扩展名)完全一致。例如,如果文件是 tomato.png,JSON中应为 "tomato"。
  3. 错误处理: getIdentifier() 方法在找不到对应资源时会返回 0。务必检查返回值,并在资源未找到时提供一个默认的占位符图片,或者记录错误日志,以避免应用崩溃并提升用户体验。
  4. 性能考量: getIdentifier() 是一个反射操作,相比直接使用 R.drawable.id 可能会有轻微的性能开销。但在 RecyclerView 的 onBindViewHolder 中适度使用通常不会造成明显的性能瓶颈,因为其开销相对较小。对于大量或高频率的资源查找,可以考虑在加载数据时一次性将所有字符串名称转换为ID并缓存起来。
  5. 替代方案(高级): 对于非常复杂的场景,可以考虑在应用启动时建立一个字符串名称到资源ID的映射(例如使用 HashMap),或者使用资源打包工具在构建时生成一个固定的映射文件。但对于大多数情况,getIdentifier() 已经足够优雅和高效。

总结

通过将Drawable资源的整数ID替换为字符串名称存储在外部数据中,并在运行时利用 Context.getResources().getIdentifier() 动态查找资源ID,我们能够有效地解决Android资源ID不稳定的问题。这种方法不仅提高了应用的健壮性,使其在不同编译版本下仍能正确加载资源,也保持了代码的清晰性和可维护性,是处理动态资源加载的推荐实践。

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
json数据格式
json数据格式

JSON是一种轻量级的数据交换格式。本专题为大家带来json数据格式相关文章,帮助大家解决问题。

454

2023.08.07

json是什么
json是什么

JSON是一种轻量级的数据交换格式,具有简洁、易读、跨平台和语言的特点,JSON数据是通过键值对的方式进行组织,其中键是字符串,值可以是字符串、数值、布尔值、数组、对象或者null,在Web开发、数据交换和配置文件等方面得到广泛应用。本专题为大家提供json相关的文章、下载、课程内容,供大家免费下载体验。

546

2023.08.23

jquery怎么操作json
jquery怎么操作json

操作的方法有:1、“$.parseJSON(jsonString)”2、“$.getJSON(url, data, success)”;3、“$.each(obj, callback)”;4、“$.ajax()”。更多jquery怎么操作json的详细内容,可以访问本专题下面的文章。

334

2023.10.13

go语言处理json数据方法
go语言处理json数据方法

本专题整合了go语言中处理json数据方法,阅读专题下面的文章了解更多详细内容。

82

2025.09.10

string转int
string转int

在编程中,我们经常会遇到需要将字符串(str)转换为整数(int)的情况。这可能是因为我们需要对字符串进行数值计算,或者需要将用户输入的字符串转换为整数进行处理。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

990

2023.08.02

js 字符串转数组
js 字符串转数组

js字符串转数组的方法:1、使用“split()”方法;2、使用“Array.from()”方法;3、使用for循环遍历;4、使用“Array.split()”方法。本专题为大家提供js字符串转数组的相关的文章、下载、课程内容,供大家免费下载体验。

739

2023.08.03

js截取字符串的方法
js截取字符串的方法

js截取字符串的方法有substring()方法、substr()方法、slice()方法、split()方法和slice()方法。本专题为大家提供字符串相关的文章、下载、课程内容,供大家免费下载体验。

220

2023.09.04

java基础知识汇总
java基础知识汇总

java基础知识有Java的历史和特点、Java的开发环境、Java的基本数据类型、变量和常量、运算符和表达式、控制语句、数组和字符串等等知识点。想要知道更多关于java基础知识的朋友,请阅读本专题下面的的有关文章,欢迎大家来php中文网学习。

1564

2023.10.24

Go高并发任务调度与Goroutine池化实践
Go高并发任务调度与Goroutine池化实践

本专题围绕 Go 语言在高并发任务处理场景中的实践展开,系统讲解 Goroutine 调度模型、Channel 通信机制以及并发控制策略。内容包括任务队列设计、Goroutine 池化管理、资源限制控制以及并发任务的性能优化方法。通过实际案例演示,帮助开发者构建稳定高效的 Go 并发任务处理系统,提高系统在高负载环境下的处理能力与稳定性。

4

2026.03.10

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Kotlin 教程
Kotlin 教程

共23课时 | 4.3万人学习

C# 教程
C# 教程

共94课时 | 11万人学习

Java 教程
Java 教程

共578课时 | 80万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号