首页 > Java > java教程 > 正文

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

花韻仙語
发布: 2025-12-05 21:39:43
原创
986人浏览过

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(原始实现)

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

Winston AI
Winston AI

强大的AI内容检测解决方案

Winston AI 138
查看详情 Winston AI

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

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

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

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