38

I tried a couple things and nothing is working... I'm trying to change the BackgroundColor on a ImageView on Android, but nothing happens...

Here is my xml:

<ImageView
   android:id="@+id/imageView1"
   android:layout_width="350dp"
   android:layout_height="550dp"
   android:layout_above="@+id/btnInfo"
   android:layout_alignLeft="@+id/fundo"
   android:layout_alignRight="@+id/btnInfo"
   android:layout_alignTop="@+id/fundo"
   android:layout_centerHorizontal="true"
   android:contentDescription="@string/backgroundMain" />

And the code:

public void onStart()
    {
        super.onStart();
        Log.d("Teste", "In the onStart() event 5");

        ImageView backgroundImg = (ImageView) findViewById(R.id.imageView1);
        backgroundImg.setBackgroundColor(Color.rgb(255, 255, 255));
    }

What am I missing?

CarinaPilar
  • 1,054
  • 2
  • 13
  • 20

5 Answers5

36

RGB:255, 255, 255 is the color code for WHITE. Since your parent layout background color is also white you won't see the difference.

Try changing color like

backgroundImg.setBackgroundColor(Color.rgb(100, 100, 50));

Or else change the background color of parent layout.

Abhishek V
  • 12,488
  • 6
  • 51
  • 63
  • Yeah, what a shame... When I realize that was the white color the problem, was too late... Thanks! ;-) – CarinaPilar Oct 19 '13 at 10:04
  • is it possible to set up both on xml file ? Changing background color with background image ? – jorge saraiva Nov 16 '17 at 15:04
  • @Abhishek V I have an image view where i use both black and white shades of 'library_add_check' icon of https://material.io/resources/icons/?search=check&icon=library_add_check&style=baseline to represent 'select all' and 'uncheck all' feature,I need the parent toolbar color(ie,different in each activity screen) for the black icon shade to represent 'uncheck all' and the white shade for 'select all', so how can i change the black icon background on change?? – KJEjava48 Feb 18 '21 at 06:34
27

There's nothing wrong with your code. But I would prefer doing this through xml , This will also solve your problem. Just add this in your ImageView tag.

android:background="@android:color/black"
ayon
  • 2,180
  • 2
  • 17
  • 32
21

In theory it should work...but try like this:

backgroundImg.setBackgroundColor(Color.parseColor("#FFFFFF"));
Alécio Carvalho
  • 13,481
  • 5
  • 68
  • 74
2

If you want to use a XML file placed in drawable folder, you might need to use:

imageView.setBackgroundResource(R.drawable.drawable);
brasofilo
  • 25,496
  • 15
  • 91
  • 179
makunomark
  • 789
  • 6
  • 10
2

Using PorterDuff.Mode:

imageView1.setColorFilter(colorCode,android.graphics.PorterDuff.Mode.SRC_IN);

PorterDuff.mode gives a way of composing and overlaying images in Android, see also What does PorterDuff.Mode mean in android graphics.What does it do?

Community
  • 1
  • 1
Sunil Chaudhary
  • 1,221
  • 12
  • 25