我想創建自定義按鈕以在TabHost中使用。我一直試圖只使用相同的圖像資源(png),但根據狀態改變colorfilter。所以我做了這個位作爲佈局自定義按鈕:StateListDrawable切換顏色過濾器
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<ImageView android:id="@+id/tab_icon"
android:layout_centerInParent="true" android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView android:id="@+id/tab_text" android:layout_below="@id/tab_icon"
android:layout_centerHorizontal="true" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
在我的活動,我添加的標籤是這樣的:
tabHost.addTab(tabHost.newTabSpec(TAB_NAME_NEWS).setIndicator(buildTab(R.drawable.tab_icon_news, R.string.news))
.setContent(newsIntent));
這是「buildTab」的方法:
private final static int[] SELECTED = new int[] { android.R.attr.state_selected };
private final static int[] IDLE = new int[] { -android.R.attr.state_selected };
private View buildTab(int icon, int label) {
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.tab_button, null);
StateListDrawable drawable = new StateListDrawable();
Drawable selected = getResources().getDrawable(icon);
selected.mutate();
selected.setBounds(0, 0, selected.getIntrinsicWidth(), selected.getIntrinsicHeight());
selected.setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0x0000FF00));
drawable.addState(SELECTED, selected);
Drawable idle = getResources().getDrawable(icon);
idle.mutate();
idle.setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0x000000FF));
drawable.addState(IDLE, idle);
((ImageView) view.findViewById(R.id.tab_icon)).setImageDrawable(drawable);
((TextView) view.findViewById(R.id.tab_text)).setText(getString(label));
return view;
}
在所選擇的狀態下,圖像應該是完全綠色(0x0000FF00
),以及在非選擇狀態時,它應該是藍色(0x000000FF
)。
問題是colorfilters似乎被完全忽略。在任何情況下,我都看不到顏色發生變化。
我還試圖通過設置在<ImageView/>
的android:tint
屬性來獲得相同的結果,但顯然你不能用一個<selector>
有一個參考,因爲它拋出一個NumberFormatException
。
我看不出我做錯了什麼,所以任何幫助將不勝感激。
假設我想製作一個imageView,它可以在xml中有新的「StateDrawable」,我該怎麼做? – 2013-08-11 12:28:49
很好的答案,但我可以建議一個改進。有'StateSet.stateSetMatches'方法,它檢查你可繪製的狀態是否匹配想要的狀態(而不是手動迭代數組) – 2013-10-12 23:52:13