Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change background color of ImageView in Android using java code

Tags:

java

android

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"/>
like image 234
Seung Joo Noh Avatar asked Mar 14 '23 17:03

Seung Joo Noh


2 Answers

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!

like image 124
Krishna Avatar answered Mar 16 '23 06:03

Krishna


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();
like image 22
Matias Elorriaga Avatar answered Mar 16 '23 07:03

Matias Elorriaga