Android 由图片名称得到资源id

我们可以这样写

Activity

ImageView img = findViewById(R.id.img);
String text = "tupianmingcheng";
img.setBackgroundResource(getResource().getIdentifier(text, "drawable", getPackageName()));

adapter,注意context

String text = "tupianmingcheng";
img.setBackgroundResource(context.getResource().getIdentifier(text, "drawable", context.getPackageName()));

Fragment,注意:需要getContext()

String text = "tupianmingcheng";
img.setBackgroundResource(getContext().getResource().getIdentifier(text, "drawable", getContext().getPackageName()));

赞 (0)

评论区

发表评论

29+23=?

暂无评论,要不来一发?

回到顶部