Reputation: 1331
I would simply like to change the colour of an imageView object using code, but it appears to be proving a lot more difficult than it sounds.
Here is my xml for the object:
<ImageView
android:id="@+id/lifeSquare"
android:layout_width="50dp"
android:layout_height="30dp"
android:background="#2a80b9"
android:visibility="invisible"
android:adjustViewBounds="false"
android:clickable="true"
android:cropToPadding="false"
android:padding="0dp"
android:scaleType="fitStart" />
It's just a blue square, as you can see. I would like to be able to change this line in code:
android:background="#2a80b9"
That's it! I have read many posts on this topic, the most promising had the following solution:
View someView = findViewById(R.id.lifeSquare);
View root = someView.getRootView();
root.setBackgroundColor(Color.parseColor("#fffff"));
But it doesn't work. It just leaves the colour exactly as it is.
Has anyone done this before, or have any better ideas?
Upvotes: 0
Views: 6326
Reputation: 1
If you are using hexcode for color and want to set the color as background of image, then this is the kotlin code.
val bitmap = Bitmap.createBitmap(30, 30, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
val colorCode = "#ffffff"
canvas.drawColor(Color.parseColor(colorCode))
mImageViewLogo.setImageBitmap(bitmap)
Upvotes: 0
Reputation: 1219
refer this code:
imageView.setColorFilter(imageView.getContext().getResources().getColor(R.color.desired_color), PorterDuff.Mode.SRC_ATOP);
Upvotes: 0
Reputation: 576
You can save all your color hex codes in color.xml
inside value folder of resources
imageView.setBackgroundColor(getResources().getColor(R.color.grey));
Upvotes: 0
Reputation: 8478
Why are you setting background
of root view. Just this statement will work :
ImageView someView = (ImageView) findViewById(R.id.lifeSquare);
someView.setBackgroundColor(Color.parseColor("#ffffff"));
Concern :
One more point is that your imageView
has visibility invisible
:
android:visibility="invisible"
Why are you setting invisible property to your imageview?
Upvotes: 6