在用作背景的Drawable xml中在运行时更改形状纯色

时间:2013-05-19 15:41:36

标签: android layout drawable shape

我有一个Drawable xml文件(background.xml):

<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <shape>
         ...........
        </shape>
    </item>

    <item android:id="@+id/shape_id">
        <shape android:shape="rectangle">
            <solid android:color="#ffefefef" /> 
        </shape>
    </item>

</layer-list>
由LinearLayout使用:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@drawable/background"
    android:id="@+id/layout_id"
    >

现在我需要根据某些条件在运行时更改形状shape_id纯色。怎么做?

1 个答案:

答案 0 :(得分:60)

我发现:

    View v = findViewById(R.id.layout_id);

    LayerDrawable bgDrawable = (LayerDrawable)v.getBackground();
    final GradientDrawable shape = (GradientDrawable)   bgDrawable.findDrawableByLayerId(R.id.shape_id);
    shape.setColor(----);