是否可以更新TabWidget图标/指示器?如果是这样,当你通过意图创建TabContent时如何?
以下编辑,感谢@Bart
通用代码:
MainActivity:
public class TestActivity extends TabActivity {
public int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//TabHost mTabHost = (TabHost) findViewById(android.R.id.tabhost);
TabHost mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec("tab1").setContent(
new Intent(this, OneActivity.class)).setIndicator("One"));
mTabHost.addTab(mTabHost.newTabSpec("tab2").setContent(
new Intent(this, TwoActivity.class)).setIndicator("Two"));
changeTitle(0, 20);
}
public void changeTitle(int cnt, int i){
View v = getTabWidget().getChildAt(cnt);
TextView tv = (TextView) v.findViewById(android.R.id.title);
tv.setText("One ("+i+")");
}
}
OneActivity(ChildActivity):
public class OneActivity extends Activity {
TextView tv;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.one);
tv = (TextView) findViewById(R.id.tv);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int i = Integer.parseInt((String) tv.getText());
i++;
tv.setText(""+i);
TestActivity parent = OneActivity.this.getParent();
parent.changeTitle(0,i);
}
});
}
}
我想在标签的标题中显示数字
答案 0 :(得分:3)
这是有可能的但是有点棘手:
ViewGroup vg = (ViewGroup) getTabHost().getTabWidget().getChildAt(0);
TextView tv = (TextView) vg.getChildAt(1);
调用getChildAt()时应注意索引。最好的方法是调试和检查。
由于1.6 TabWidget有一个方法getChildTabViewAt,所以你可以跳过第一行并写下:
ViewGroup vg = (ViewGroup) getTabHost().getTabWidget().getChildTabViewAt(0);
View tabIndicator = inflater.inflate(R.layout.tab_indicator,
mTabWidget, // tab widget is the parent
false); // no inflate params
final TextView tv = (TextView) tabIndicator.findViewById(R.id.title);
tv.setText(mLabel);
final ImageView iconView = (ImageView) tabIndicator.findViewById(R.id.icon);
iconView.setImageDrawable(mIcon);
如您所见,它包含TextView和ImageView。
答案 1 :(得分:2)
尝试像这样获取imageView
ImageView v = (ImageView)tabActivity.getTabHost().getTabWidget().getChildTabViewAt(i).findViewById(android.R.id.icon);
v.setImageDrawable(getResources().getDrawable(R.drawable.newIcon));
答案 2 :(得分:0)
给出标题和图标的数组
for (int i = 0; i < numTabs; i++ ) {
TabSpec spec = host.newTabSpec(String.valueOf(i)); //sets tab index
Drawable icon = res.getDrawable(icons[i]); //sets the icon
// set tab text and icon
spec.setIndicator(titles[i], icon); //sets the title
host.addTab(spec);
}