如何为 TabHost 背景动态更改 shapedrawable 颜色?

How to change shapedrawable color dynamically for TabHost background?

我有一个 TabHost,我在其中使用形状 xml 使其看起来像这样:

我这样定义TabHost背景:

private void setTabColor(TabHost tabHost) {
    try {

        for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
            tabHost.getTabWidget().getChildAt(i).setBackgroundResource(R.drawable.strib_tab);
        }

    } catch (ClassCastException e) {
    }
}

其中 strib_tab 是:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/line_pressed" android:state_selected="true"/>
<item android:drawable="@drawable/line"/>
</selector>

和line_pressed是:

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

    <item>
        <shape android:shape="rectangle" >
            <stroke
                android:width="5dip"
                android:color="@color/blue_bg" />

            <padding
                android:bottom="0dip"
                android:left="0dip"
                android:right="0dip"
                android:top="0dip" />
        </shape>
    </item>
    <item
        android:bottom="5dp"
        android:top="0dp">
            <shape android:shape="rectangle" >
            <solid android:color="#FFFFFF" />
        </shape>
    </item>

</layer-list>

行是:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <solid android:color="@android:color/transparent" />
        </shape>
    </item>
</selector>

如何动态更改 line_pressed 中颜色为 blue_bg 的形状的颜色?

您似乎无法修改 StateListDrawable,但是您可以轻松地创建新的。

至于LayerDrawable,可以很容易地操纵。

代码说话更好,所以这里是:

Resources r = getResources();

// Modify the LayerDrawable (line_pressed)
LayerDrawable ld = (LayerDrawable) r.getDrawable(R.drawable.line_pressed);
GradientDrawable gradient = (GradientDrawable) ld
            .findDrawableByLayerId(R.id.stroke);
// Set a custom stroke (width in pixels)
gradient.setStroke(5, Color.RED);

// Create a new StateListDrawable
StateListDrawable newStripTab = new StateListDrawable();
newStripTab.addState(new int[] { android.R.attr.state_selected }, ld);
newStripTab.addState(new int[0], r.getDrawable(R.drawable.line));

tabHost.getTabWidget().getChildAt(i).setBackgroundResource(newStripTab);

备注:

  • 我用的是自定义的line_pressed,所以很容易找到特定的图层:

    <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
        <item android:id="@+id/stroke">
            <shape android:shape="rectangle" >
                <stroke
                    android:width="5dip"
                    android:color="#000" />
                ...
            </shape>
        </item>
        ...     
    </layer-list>
    
  • 此代码未经实际测试,但应该可以工作或至少提供一些关于如何实现此目的的见解。