新闻中心

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

2025-12-05
浏览次数:
返回列表

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

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

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

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

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

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

Recipe.j*a 数据类

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.j*a 数据类(原始设计)

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.j*a(原始实现)

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 异常。

Moshi Chat Moshi Chat

法国AI实验室Kyutai推出的端到端实时多模态AI语音模型,具备听、说、看的能力,不仅可以实时收听,还能进行自然对话。

Moshi Chat 160 查看详情 Moshi Chat

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

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

这个方法接受三个参数:

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

步骤一:修改数据类 (Ingredient.j*a)

将 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.j*a)

在 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不稳定的问题。这种方法不仅提高了应用的健壮性,使其在不同编译版本下仍能正确加载资源,也保持了代码的清晰性和可维护性,是处理动态资源加载的推荐实践。

以上就是Android应用中通过字符串名称动态加载Drawable资源教程的详细内容,更多请关注其它相关文章!


# 转换为  # 网站推广火丶星22好  # 南京网站优化哪家好  # 建设网站工作量大  # seo刷工具 site  # 均安电气网站建设  # 东莞建材网站seo优化  # 广州网站建设搭建方案  # seo主词和关键词  # 孝感网站推广优化公司  # 深圳网站建设送域名  # 会有  # 就会  # 时长  # 不稳定  # 好了  # java  # 是一个  # 数据结构  # 并在  # 加载  # red  # string类  # 性能瓶颈  # 应用开发  # google  # 工具  # go  # json  # js  # android 


相关栏目: 【 科技资讯46185 】 【 网络学院92790


相关推荐: 腾讯视频怎么使用多账号家庭管理_腾讯视频家庭多账号统一管理与权限分配教程  在J*a中如何使用Stream.map转换元素_Stream映射操作解析  iwriter统一登录平台 iwrite账号密码登录页面  机构:以往存储涨价周期小米利润率实际上有所改善 能转嫁给消费者等  Golang如何优雅处理error_Golang error处理最佳实践总结  2026春节假期票务安排_2026春节放假购票指南  如何设置Windows Defender的定时扫描_计划任务实现自动杀毒【安全】  一加Ace 6T支持全新明眸护眼:通过了最严苛的护眼小金标认证  文本文档写html代码怎么运行_文本文档html代码运行步骤【教程】  在J*a中如何捕获IndexOutOfBoundsException_索引越界异常防护方法说明  单射、满射与双射的关系 一文理清所有逻辑  千牛数据看板网页版_千牛数据看板网页版访问方法  58动漫网在线官方网 58动漫网正版动漫入口网址  Surface怎么安装系统 微软Surface Pro U盘重装win11教程  支付宝解绑银行卡步骤_支付宝如何解除绑定银行卡  优酷会员付费后没到账怎么办_优酷会员充值异常及解决方法  抖音怎么赚钱_抖音创作者变现方法与途径指南  Win11怎么安装Linux子系统 Win11 WSL2安装Ubuntu及环境配置指南  Sublime Text怎么显示空格和制表符_Sublime显示不可见字符设置  Google翻译怎么语音输入_Google翻译语音输入功能使用与设置方法  荒野行动PC版怎么注册_荒野行动PC版账号注册详细流程图文教程  Discord Slash 命令响应超时问题的异步解决方案  Excel文件在线转换快速入口 Excel在线格式转换网站  LINUX的perf命令入门_LINUX官方性能分析工具的使用与解读  苹果手机指南针不准怎么校准 传感器校准方法详解【建议收藏】  汽水音乐在线解析 汽水音乐在线解析入口  漫蛙官网正版漫画入口 漫蛙2官方网页登录地址  TikTok搜索不到用户发布内容怎么办 TikTok用户内容搜索优化方法  现代化 SciPy 一维插值:interp1d 的替代方案与最佳实践  J*a编写用户注册与登录功能_掌握字符串与验证逻辑  谷歌浏览器无痕模式怎么开 Chrome开启无痕浏览设置方法【教程】  GemBox Document HTML转PDF垂直文本渲染问题及解决方案  在J*a中如何开发在线活动报名与管理系统_活动报名管理项目实战解析  AO3网页版合集入口 Archive of Our Own同人作品浏览指南  如何在Promise链中优雅地中断后续then执行  菜鸟取件码是什么怎么查 最全查询渠道汇总  修复二维数组索引越界异常:一维循环到二维坐标的正确映射  在Typer应用中优雅地处理和重组任意命令行参数  Go调试环境为何无法启动_Go调试器启动失败原因与解决策略  优化 Python 函数中的条件逻辑:解决 if-else 嵌套与参数选择问题  J*a应用程序首次运行自动创建文件与目录的最佳实践  Win10桌面图标出现小盾牌怎么办 Win10去除UAC图标教程【解决】  深入理解字体排版:Adobe光学字偶距与CSS字偶距的差异与实现  Win11怎么设置开机NumLock亮 Win11修改注册表InitialKeyboardIndicators值  在Go开发中优雅管理ListenAndServe进程:GoSublime集成方案  抖音网页版平台入口 抖音网页版官网在线访问教程  漫蛙manwa官网登录界面_漫蛙漫画网页版主站入口  如何优雅地解决Livewire文件上传难题?SpatieLivewireFilepond让一切变得简单  打开就能玩的植物大战僵尸 植物大战僵尸网页版传送门  俄罗斯搜索引擎Yandex指南 附2025年免登录官网入口 

搜索