从代码中更改布局的背景颜色

时间:2015-01-14 12:54:20

标签: java android xml android-linearlayout android-drawable

我的视图具有已定义的可绘制背景(使其成为圆形)并为其提供基本背景颜色:
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>
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">

我尝试仅更改代码中的背景颜色,但它不起作用 的 MainActivity.java:

private LinearLayout container;
// on create
container = (LinearLayout) findViewById(R.id.result_container);
container.setBackgroundColor(0x4CAF50);

但它只是变白了。保持椭圆形很重要。

3 个答案:

答案 0 :(得分:3)

在res / values文件夹中创建colors.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="blue">#ff64c2f4</color>
</resources>

然后:

container.setBackgroundColor(getResources().getColor(R.color.blue));

答案 1 :(得分:2)

这里

  

container.setBackgroundColor(0x4CAF50);

此行将使用circle_block.xml

替换您在xml中设置的背景

因此,如果您想更改布局背景可绘制颜色,请使用Drawable.setColorFilter

Drawable drawable = getResources().getDrawable(R.drawable.circle_block);
drawable.setColorFilter(0x4CAF50, PorterDuff.Mode.SRC_ATOP);
container.setBackgroundDrawable(drawable);

这将改变当前布局背景中的形状颜色

答案 2 :(得分:0)

在linearlayout包含自定义背景

时尝试按照
GradientDrawable drawable = container.getBackground();
drawable.setColor(yourcolorvalue);