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"/>
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!
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With