简体   繁体   中英

Change the background color of a layout from the code

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.

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));

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

Try following as you linearlayout consist of custom background

GradientDrawable drawable = container.getBackground();
drawable.setColor(yourcolorvalue);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM