在 JSON 文件中,我有数据和可绘制字符串:
{"title": "title1","thumb": "R.drawable.image1"},{"title": "title2","thumb": "R.drawable.image2"}
我正在解析它
JSONObject obj = myjArry.getJSONObject(i);
String thumb = obj.getString("thumb");
然后我尝试将可绘制对象分配给我的适配器中的 ImageView:
int tm = Integer.parseInt(actorList.get(position).getThumb());
holder.thumb.setImageResource(tm);
问题是,我无法将文本字符串转换为 int,因为它不是数字,但
setImageResource
需要整数。
现在我有这个错误:
java.lang.NumberFormatException: For input string: "R.drawable.image1"
PS:如果可以的话,不要使用
getIdentifier()
,因为不鼓励使用。
您需要使用 Resources#getIdentifier 方法来使用资源名称获取 id,例如:
String name = actorList.get(position).getThumb();
Resources res = context.getResources();
Drawable drawable = res.getDrawable(res.getIdentifier(name, "drawable", context.getPackageName()));
holder.thumb.setImageDrawable(drawable);