How to remove tab from TabHost

2019-01-09 10:00发布

问题:

In a TabHost widget, I can create a new tab with its content (Intent) using TabHost.addTab(TabHost.TabSpec tabSpec).

We can remove all tabs we created by calling clearAllTabs(), but I can't figure out how to remove the tab or just replace the content (Intent) inside the tab with new Intent.

so what I need something like removeTab(int index)

回答1:

Actually, clearAllTabs does that :

public void clearAllTabs() {
  mTabWidget.removeAllViews();
  initTabHost();
  mTabContent.removeAllViews();
  mTabSpecs.clear();
  requestLayout();
  invalidate();
}

And the method removeAllViews comes from the class ViewGroup. Luckily, ViewGroup does have methods to remove only one view :

  • removeView(View view)
  • removeViewAt(int index)
  • removeViewInLayout(View view)

Knowing that, I would recommend to subclass TabWidget and TabHost to add the behaviour you need. Maybe there is an easier way but that's the only one I can think of. Good luck



回答2:

Much Easier:

 tabHost.getTabWidget().removeView(tabHost.getTabWidget().getChildTabViewAt(3));