4

I am having troubles with this code. I am trying to change my background color of my ImageView through java code. When I try this, there is no change at all in the imageView. I tried to change the background color through xml and it worked fine. But through java, it does not work. why is that? is there anything wrong with my code?

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    buttonClick();
}
public void buttonClick(){
    ImageView imgView1 = (ImageView) findViewById(R.id.image0);// i have an imageView in my resources in XMl.
    imgView1.setBackgroundColor(Color.RED);
}

This is my part of xml

<RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<GridLayout
    android:layout_width="match_parent"
    android:layout_height="400dp"
    android:columnCount="3"
    android:rowCount="3"
    android:id="@+id/gridLayout"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentEnd="true">
    <ImageView
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        android:id="@+id/image0"
        android:layout_row="0"
        android:layout_column="0"/>
1
  • so what is the problem? do u get any error? do you see something weird? please elaborate on your question Commented Jan 2, 2016 at 19:34

2 Answers 2

5

You can either use

imageView.setBackgroundColor(getResources().getColor(R.id.your_color));


imageView.setBackgroundColor(Color.parse("#your_color"));

In api level 23 you can use ContextCompat provides getColor method:

  imageView.setBackgroundColor(ContextCompat.getColor(context,R.id.your_color));

All above mentioned methods will work fine. Hope this helps!

Sign up to request clarification or add additional context in comments.

2 Comments

It still doesn't work... and I want to know why imgView1.setBackgroundColor(Color.RED); doesn't work....please help me
If you observe it accepts object and not the resource id . If you use resource id directly android will not identify it as colour. You should use above recommended methods. Android studio also shows warning when you directly specify colour id.
3

please try with

backgroundImg.setBackgroundColor(Color.parseColor("#ff0000"));

or

backgroundImg.setBackgroundColor(Color.rgb(255, 0, 0));

also, you may need to invalidate the view after setting the color:

backgroundImg.invalidate();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.