Reputation: 6641
I have a view that has a defined drawable background (that makes it a circle) and gives it a basic background color:
circle_block.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
android:color="#aaaaaa" />
</shape>
in the activity_main.xml:
<LinearLayout
android:id="@+id/result_container"
android:background="@drawable/circle_block"
android:orientation="vertical"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_marginTop="15dp"
android:gravity="center"
android:layout_gravity="center">
I tried changing only the background color from the code, but it didn't work.
MainActivity.java:
private LinearLayout container;
// on create
container = (LinearLayout) findViewById(R.id.result_container);
container.setBackgroundColor(0x4CAF50);
But it just turns white. It's important to retain to oval shape.
Upvotes: 1
Views: 3546
Reputation: 132992
here
container.setBackgroundColor(0x4CAF50);
This line will replace background which you are setting in xml using circle_block.xml
So if you want to change layout background drawable color then use Drawable.setColorFilter
:
Drawable drawable = getResources().getDrawable(R.drawable.circle_block);
drawable.setColorFilter(0x4CAF50, PorterDuff.Mode.SRC_ATOP);
container.setBackgroundDrawable(drawable);
this will change color of shape which is currently in background of Layout
Upvotes: 2
Reputation: 3843
Try following as you linearlayout consist of custom background
GradientDrawable drawable = container.getBackground();
drawable.setColor(yourcolorvalue);
Upvotes: 0
Reputation: 109
Create colors.xml file in res/values folder:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="blue">#ff64c2f4</color>
</resources>
And then:
container.setBackgroundColor(getResources().getColor(R.color.blue));
Upvotes: 3