我有一个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的形状颜色?
答案 0 :(得分:3)
您似乎无法修改StateListDrawable
,但您可以轻松创建新的。{/ p>
至于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>
此代码实际上未经测试,但应该有效或至少提供一些有关如何实现此目的的见解。