TabHost 添加Tab项:
- tabhost = this.getTabHost();
- TabSpec tabSpec = tabhost.newTabSpec("news");
- tabSpec.setIndicator("新闻");
- tabSpec.setContent(new Intent(this, NewsActivity.class));
- tabhost.addTab(tabSpec);
- TabSpec tabSpec2 = tabhost.newTabSpec("fun");
- tabSpec2.setIndicator("娱乐");
- tabSpec2.setContent(new Intent(this,FunActivity.class));
- tabhost.addTab(tabSpec2);
- TabSpec tabSpec3 = tabhost.newTabSpec("sport");
- tabSpec3.setIndicator("体育");
- tabSpec3.setContent(new Intent(this,SportsActivity.class));
- tabhost.addTab(tabSpec3);
- TabSpec tabSpec4 = tabhost.newTabSpec("setting");
- tabSpec4.setIndicator("设置");
- tabSpec4.setContent(new Intent(this, SettingActivity.class));
- tabhost.addTab(tabSpec4);
TabHost删除Tab项
- mTabHost.getTabWidget().removeViewAt(mTabHost.getCurrentTab());
这样删除会有问题。
只能通过删除所有Tab项然后再依次添加。需要注意在调用clearAllTabs()方法之前,需要设置当前显示的tab,即setCurrentTab(0),否则出现空指针问题。
完整代码如下:
- tabhost.setCurrentTab(0);
- tabhost.clearAllTabs();
- TabSpec tabSpec = tabhost.newTabSpec("news");
- tabSpec.setIndicator("新闻");
- tabSpec.setContent(new Intent(this,
- NewsActivity.class));
- tabhost.addTab(tabSpec);
- TabSpec tabSpec2 = tabhost.newTabSpec("fun");
- tabSpec2.setIndicator("娱乐");
- tabSpec2.setContent(new Intent(this,
- FunActivity.class));
- tabhost.addTab(tabSpec2);
- TabSpec tabSpec3 = tabhost.newTabSpec("sport");
- tabSpec3.setIndicator("体育");
- tabSpec3.setContent(new Intent(this,
- SportActivity.class));
- tabhost.addTab(tabSpec3);
- TabSpec tabSpec4 = tabhost.newTabSpec("setting");
- tabSpec4.setIndicator("设置");
- tabSpec4.setContent(new Intent(EarthActivity.this,
- SettingActivity.class));
- tabhost.addTab(tabSpec4);
- tabhost.setCurrentTab(2);