You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中用for循环填充ArrayList失败的原因及优化方案咨询

你的问题分析与优化方案

你的理解完全正确!问题出在R类的资源ID是编译时生成的整数常量,而你直接把字符串"R.drawable.porridge1"转成整数的操作完全行不通——Integer.parseInt()只会把这个字符串当作普通数字解析,显然和实际的资源ID数值毫无关系,运行时大概率会抛出NumberFormatException,或者拿到一个无效的ID导致后续出错。

下面给你两种可行的优化方案,兼顾简洁性和安全性:

方案一:使用getIdentifier()动态获取资源ID

Android提供了getResources().getIdentifier()方法,可以通过资源名称、类型和包名动态查找对应的资源ID。这种方法适合资源命名规则固定、数量较多的场景:

for (int i = 1; i < 4; i++) {
    // 动态获取各类型资源ID
    int picId = getResources().getIdentifier("porridge" + i, "drawable", getPackageName());
    int nameId = getResources().getIdentifier("recipe_name_" + i, "string", getPackageName());
    int shortDescId = getResources().getIdentifier("recipe_short_" + i, "string", getPackageName());
    int ingredientsId = getResources().getIdentifier("recipe_ingridients_" + i, "string", getPackageName());
    int longDescId = getResources().getIdentifier("recipe_long_" + i, "string", getPackageName());

    // 校验资源是否存在(返回0表示未找到)
    if (picId != 0 && nameId != 0 && shortDescId != 0 && ingredientsId != 0 && longDescId != 0) {
        recyclerViewItems.add(new RecyclerViewItem(
            picId,
            getString(nameId),
            getString(shortDescId),
            getString(ingredientsId),
            getString(longDescId)
        ));
    }
}

注意:getIdentifier()是运行时查找,性能略低于直接使用常量ID,所以如果资源数量不多,更推荐下面的方案。

方案二:使用资源ID数组(更高效安全)

把对应的资源ID预先存入数组,循环遍历数组添加元素。这种方法编译时就能校验资源是否存在,性能也更好:

// 预先定义资源ID数组,和你的资源命名一一对应
int[] recipePicIds = {R.drawable.porridge1, R.drawable.porridge2, R.drawable.porridge3};
int[] recipeNameIds = {R.string.recipe_name_1, R.string.recipe_name_2, R.string.recipe_name_3};
int[] recipeShortIds = {R.string.recipe_short_1, R.string.recipe_short_2, R.string.recipe_short_3};
int[] recipeIngredientsIds = {R.string.recipe_ingridients_1, R.string.recipe_ingridients_2, R.string.recipe_ingridients_3};
int[] recipeLongIds = {R.string.recipe_long_1, R.string.recipe_long_2, R.string.recipe_long_3};

// 循环遍历数组添加元素
for (int i = 0; i < recipePicIds.length; i++) {
    recyclerViewItems.add(new RecyclerViewItem(
        recipePicIds[i],
        getString(recipeNameIds[i]),
        getString(recipeShortIds[i]),
        getString(recipeIngredientsIds[i]),
        getString(recipeLongIds[i])
    ));
}

小提示

注意你代码里的拼写:ingridients是常见拼写错误(正确应为ingredients),如果后续要修改资源名,记得统一修正,避免资源查找失败。

内容的提问来源于stack exchange,提问作者BerZerg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 18:27:51