[英]Android change Tab image (not background)
我正在使用具有 3 个选项卡的 TabHost。 每个选项卡都有一个图像 + 文本。
spec = tabHost.newTabSpec("MyTasks")
.setIndicator(Html.fromHtml("<b><H2>My Tasks</H2></b>"), getResources().getDrawable(R.drawable.task ))
.setContent(intent);
tabHost.addTab(spec);
我想在 select 标签时更改图像。 我用下面的代码来改变它......
TabWidget tw = getTabWidget();
View leftTabView = tw.getChildAt(0);
leftTabView.setBackgroundDrawable(getResources().getDrawable(R.drawable.tab1_drawable));
tab1_drawable 是一个 xml(每个状态的选择器和项目)。 这是设置和更改背景,而不是我设置的图像。 我该如何改变它?
与其通过代码更改可绘制对象,不如使用状态列表可绘制对象? 然后,您只需在选项卡被选中时为其指定一个不同的可绘制对象。
例如,ic_tab_tasks.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ic_tab_tasks_selected"
android:state_selected="true" />
<item android:drawable="@drawable/ic_tab_tasks_normal" />
</selector>
然后,当您最初设置选项卡指示器的可绘制对象时,只需使用状态列表可绘制对象即可。
试试这个:
private int index_tab = 0;
private TabWidget tabWidget;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.index_layout);
TabHost t = (TabHost)findViewById(R.id.testhost);
t.setOnTabChangedListener(new OnTabChangeListener() {
@Override
public void onTabChanged(String tabId) {
tabChanged(tabId);
}
});
}
public void tabChanged(String tabId) {
if (index_tab != (Integer.valueOf(tabId) - 1)) {
tabWidget.getChildAt(Integer.valueOf(tabId) - 1)
.setBackgroundDrawable(
getResources().getDrawable(R.drawable.tab1_drawable));
tabWidget.getChildAt(index_tab).setBackgroundDrawable(null);
index_tab = Integer.valueOf(tabId) - 1;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.