比如项目中有四个tab,但无论setcurrent(2或者3)第一个tab必须会跟着初始化,怎样能不加载第一个tab呢。
解决办法如下:
1、起首查看addTab(TabSpec tabSpec)源代码:
/**
* Add a tab.
* @param tabSpec Specifies how to create the indicator and content.
*/
public void addTab(TabSpec tabSpec) {
if (tabSpec.mIndicatorStrategy == null) {
throw new IllegalArgumentException("you must specify a way to create the tab indicator.");
}
if (tabSpec.mContentStrategy == null) {
throw new IllegalArgumentException("you must specify a way to create the tab content");
}
View tabIndicator = tabSpec.mIndicatorStrategy.createIndicatorView();
tabIndicator.setOnKeyListener(mTabKeyListener);
// If this is a custom view, then do not draw the bottom strips for
// the tab indicators.
if (tabSpec.mIndicatorStrategy instanceof ViewIndicatorStrategy) {
mTabWidget.setStripEnabled(false);
}
mTabWidget.addView(tabIndicator);
mTabSpecs.add(tabSpec);
if (mCurrentTab == -1) {
setCurrentTab(0);
}
}
发现进行addTab操纵时,默认履行了最后一步,设置了第一个tab,所以我们须要改变CurrentTab的值,设置为不为-1的一个数,且大于0。
2、再看setCurrentTab(int index)办法源码:
public void setCurrentTab(int index) {
if (index < 0 || index >= mTabSpecs.size()) {
return;
}
if (index == mCurrentTab) {
return;
}
// notify old tab content
if (mCurrentTab != -1) {
mTabSpecs.get(mCurrentTab).mContentStrategy.tabClosed();
}
mCurrentTab = index;
final TabHost.TabSpec spec = mTabSpecs.get(index);
// Call the tab widget""s focusCurrentTab(), instead of just
// ing the tab.
mTabWidget.focusCurrentTab(mCurrentTab);
// tab content
mCurrentView = spec.mContentStrategy.getContentView();
if (mCurrentView.getParent() == null) {
mTabContent
.addView(
mCurrentView,
new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
}
if (!mTabWidget.hasFocus()) {
// if the tab widget didn""t take focus (likely because we""re in touch mode)
// give the current tab content view a shot
mCurrentView.requestFocus();
}
//mTabContent.requestFocus(View.FOCUS_FORWARD);
invokeOnTabChangeListener();
}
当mCurrentTab不为-1的时辰会执行mTabSpecs.get(mCurrentTab).mContentStrategy.tabClosed()操纵,所以在我们履行setCurrentTab()办法之前,我们再把mCurrentTab的值恢复为-1,如许就不会履行封闭操纵导致空指针异常。
3、具体解决办法如下:
// 使tabhost不加载第一个tab。
try
{
Field idcurrent = tabHost.getClass().getDeclaredField("mCurrentTab");
idcurrent.setAccessible(true);
idcurrent.setInt(tabHost, 0);
}catch (Exception e){
e.printStackTrace();
}
// 添加tab
TabHost.TabSpec tSpecCoupon = tabHost.newTabSpec("sth");
tSpecCoupon.setIndicator(tabIndicator1);
tSpecCoupon.setContent(new DummyTabContent(getBaseContext()));
tabHost.addTab(tSpecCoupon);
//再把mCurrentTab恢复到-1状况
try
{
Field idcurrent = tabHost.getClass().getDeclaredField("mCurrentTab");
idcurrent.setAccessible(true);
idcurrent.set(tabHost, -1);
}catch (Exception e){
e.printStackTrace();
}
tabHost.setCurrentTab(index);
具体思路是:在添加tab前,把mCurrentTab的值改成 != -1,然后在添加tab后,把mCurrentTab的值改回 -1,最后再
setCurrentTab(index)。