How to replace R.drawable.“someString”

后端 未结 6 979
长发绾君心
长发绾君心 2021-02-02 10:00

I have some Images in my project. The name of the image is stored in a String and I would like to setImageResource(R.drawable.\".....\"); with the string of the image name but t

6条回答
  •  死守一世寂寞
    2021-02-02 10:13

    this is not a right syntax, and you must getting compiler time error, before altering image resource you must know that, all resources provided an id, these ids are stored into R.java file. Ids are stored into integer format, and in your application you can fetch all these resources by these id, not by name, so you need to fetch id of resource at first, by:

    String mDrawableName = "myimg";
    int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
    

    and then use this resID.

提交回复
热议问题