How to replace R.drawable.“someString”

后端 未结 6 980
长发绾君心
长发绾君心 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:12

    I got it working by moving the image from 'drawable' to 'raw' folder and access the string value as below. If you do not have 'raw' folder under 'res' directory, right click on res->new->Android resource directory and under dropdown of resourcetype, select 'raw'.

        String avatar = ("android.resource://" + "yourPackageName/" + String.valueOf(R.raw.robot_blue));
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-02 10:24

    Use

    getResources().getIdentifier("NAME_OF_IMAGE", "drawable", context.getPackageName())
    
    0 讨论(0)
  • 2021-02-02 10:27

    public int getIdentifier(String name, String defType, String defPackage);

    name - name of the image
    defType - it will be drawable for your case
    defPackage - default package of your app (I think you can use getPackage() on the activity for this)

    0 讨论(0)
  • 2021-02-02 10:36

    See this thread. It should help you. Basically you need to get the identifier and then load using setImageResource.

    0 讨论(0)
  • 2021-02-02 10:38

    try this

       String uri = "NAME";
    
        // int imageResource = R.drawable.icon;
        int imageResource = getResources().getIdentifier(uri, null, getPackageName());
    
        ImageView imageView = (ImageView) findViewById(R.id.myImageView);
        Drawable image = getResources().getDrawable(imageResource);
        imageView.setImageDrawable(image);
    
    0 讨论(0)
提交回复
热议问题