Android 由图片名称得到资源id

under Android  tag     Published on November 4th , 2020 at 09:05 pm

我们可以这样写

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()));

本文由 surface 创作,采用 知识共享署名4.0 国际许可协议进行许可,转载前请务必署名
  文章最后更新时间为:November 7th , 2020 at 10:28 am
分享到:Twitter  Weibo  Facebook