
在android开发中,将drawable资源id直接存储在外部数据(如json)中会导致运行时错误,因为这些id在不同编译版本中不稳定。本教程将详细介绍如何通过在json中存储drawable资源的字符串名称,并在运行时使用 `getresources().getidentifier()` 方法动态获取正确的资源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 异常。
为了解决Drawable资源ID不稳定的问题,我们应该在外部数据中存储资源的名称(字符串),而不是其整数ID。在运行时,我们可以利用Android Context 提供的 getResources().getIdentifier() 方法,根据资源的名称动态查找并获取其当前的整数ID。
这个方法接受三个参数:
将 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中的 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" // 修改为字符串名称
}
]
}在 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);
}
}
}通过将Drawable资源的整数ID替换为字符串名称存储在外部数据中,并在运行时利用 Context.getResources().getIdentifier() 动态查找资源ID,我们能够有效地解决Android资源ID不稳定的问题。这种方法不仅提高了应用的健壮性,使其在不同编译版本下仍能正确加载资源,也保持了代码的清晰性和可维护性,是处理动态资源加载的推荐实践。
以上就是Android应用中通过字符串名称动态加载Drawable资源教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号