【发布时间】:2011-08-26 11:47:58
【问题描述】:
我想创建自定义按钮以在 TabHost 中使用。我一直在尝试仅使用相同的图像资源(png),但根据状态更改滤色器。所以我做了这个位作为自定义按钮的布局:
<?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)。
问题是滤色器似乎被完全忽略了。在任何情况下我都看不到颜色的变化。
我还尝试通过在<ImageView/> 上设置android:tint 属性来获得相同的结果,但显然您不能在此处使用对<selector> 的引用,因为它会引发NumberFormatException。
我看不出我做错了什么,因此我们将不胜感激。
【问题讨论】:
标签: java android android-layout android-tabhost colorfilter