Search code examples
androidandroid-resources

Get color of ImageView


I want to get the color ID of an imageView that I have set its color before.

ImageView im = findViewById(R.id.imageView);
im.setBackgroundColor(R.color.green);

How do I do this?

int colorId = im.getBackgroundColorResourceId() // how do I do this?

Solution

  • There is no function in the ImageView class to retrieve the color of the ImageView, as they are not designed to be given a color but instead are designed to be given an image to display (hence the name, ImageView). If you want to be able to retrieve what color the ImageView has been set to, you could create your own custom ImageView class with the wanted functionality.

    import android.content.Context;
    import android.util.AttributeSet;
    import android.widget.ImageView;
    
    public class CustomImageView extends ImageView {
    
        int backgroundColor;
    
        public CustomImageView(Context context) {
            super(context);
        }
    
        public CustomImageView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public CustomImageView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        @Override
        public void setBackgroundColor(int color) {
            super.setBackgroundColor(color);
            backgroundColor = color;
        }
    
        public int getBackgroundColor() {
            return backgroundColor;
        }
    }
    

    This custom class, CustomImageView, will override the function setBackgroundColor(int color) and in doing so store the color to a variable as well as set the background color so that it can be retrieved later. The function getBackgroundColor() can be used to retrieve this variable.

    This is not the simplest solution, and I am sure there are many others, but this one made the most sense to me.