以编程方式为形状分配颜色

Programmatically assign color to shape

我有这样的布局:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/user_color">
        <shape android:shape="rectangle">
            <solid android:color="#000000" />
        </shape>
    </item>
    <item android:right="25dp">
        <shape android:shape="rectangle">
            <solid android:color="@color/user_background" />
        </shape>
    </item>
</layer-list>

我如何调用形状:

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/shape">

如何以编程方式更改 ID 为 user_color 的矩形的颜色?

试试下面的代码:

GradientDrawable bgShape = (GradientDrawable)notesLayout.getBackground();
bgShape.setColor(Color.BLACK);
int colorToPaint = getResources().getColor(android.R.color.white);// any color you want
Drawable tempDrawable = getResources().getDrawable(R.drawable.xml_layout);
LayerDrawable bubble = (LayerDrawable) tempDrawable; //cast to root element in xml
GradientDrawable solidColor = (GradientDrawable) bubble.findDrawableByLayerId(R.id.user_color);
solidColor.setColor(colorToPaint);

Anitha 的替代方案是-

如果 LayerDrawable 已经设置为您的 ImageView 使用下面的代码。

LinearLayout mLinearLayout = (LinearLayout)findViewById(R.id.my_linear_layout);
((LayerDrawable)mLinearLayout.getBackground()).findDrawableByLayerId(R.id.user_color).setColorFilter(getResources().getColor(R.color.white),PorterDuff.Mode.SRC_IN);

这样,如果您已经有了对 LinearLayout 的引用,您只需一行即可完成整个颜色更改。您甚至不需要调用 setBackground() 来显示更改!

    @user5262809
         // add id to your linear layout

        <LinearLayout 
        android:id="@+id/linearLayout"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@drawable/shape">

        // then in code do this :
        LinearLayout linearView = (LinearLayout) findViewById(R.id.linearLayout);

        // added Anitha's code here
    int colorToPaint = getResources().getColor(android.R.color.white);// any color you want
    Drawable tempDrawable =    getResources().getDrawable(R.drawable.xml_layout);
    LayerDrawable bubble = (LayerDrawable) tempDrawable; //cast to root element in xml
    GradientDrawable solidColor = (GradientDrawable) bubble.findDrawableByLayerId(R.id.user_color);
solidColor.setColor(colorToPaint);
    // and then do this 
    linearView.setBackground(tempDrawable);



    // hope this helps you :)