Search code examples
androidandroid-studioandroid-recyclerviewimageview

How can I get the integer value of R.id.image?


While using recycler views, I just want to pass the string values of resource id's of the images, but I know that it can't be done using the usual way, like we cannot pass a string in setImageResource(). But is there a way to convert the R.id.anyImage into its integer value?


Solution

  • Unfortunately, there is no getImageResource() or getDrawableId(). But, You can create simple workaround by using the ImageView tags.

    In onCreate():

    imageView0 = (ImageView) findViewById(R.id.imageView0);
    imageView1 = (ImageView) findViewById(R.id.imageView1);
    imageView2 = (ImageView) findViewById(R.id.imageView2);
    
    imageView0.setTag(R.drawable.apple);
    imageView1.setTag(R.drawable.banana);
    
    imageView2.setTag(R.drawable.cereal);
    

    Then, if you like, you can create a simple function to get the drawable id:

    private int getDrawableId(ImageView iv) 
    {
    return (Integer) iv.getTag();
    }
    

    Too easy.