【问题标题】:Change the background color of a layout from the code从代码更改布局的背景颜色
【发布时间】:2015-01-14 12:54:20
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 感谢您的快速回答!它实际上改变了背景颜色,但它破坏了椭圆形。布局必须保持圆形。我可以这样做吗?
    【解决方案2】:

    这里

    container.setBackgroundColor(0x4CAF50);

    此行将替换您在 xml 中使用 circle_block.xml 设置的背景

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

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

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

    【讨论】:

    • 嘿,这不会改变背景颜色。无论如何,谢谢你的回答。
    • @Gofilord:您正在使用不可见的0x4CAF50。用Color.RED检查它
    • 嗯,这确实有效。但我看不出我的颜色有什么问题。如何应用十六进制颜色代码?
    • 好吧,我想通了。我只需要使用Color.parseColor(mycolorstring)
    【解决方案3】:

    当您的线性布局包含自定义背景时,请尝试以下操作

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-15
      • 2015-03-29
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      相关资源
      最近更新 更多