项目中tabhost中有四个intent,其中第一个用到了开启蓝牙,结果就我第一次点开第几个都会打开蓝牙,很麻烦,所以想要把tabhost中默认设置的加载第一个tab个去掉,看了看add的源码:
/**
* 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);
}
}
注意查看这段代码
if (mCurrentTab == -1) {
setCurrentTab(0);
}
找到mCurrentTab的定义
protected int mCurrentTab = -1; 默认为-1,所有我们在添加切换卡页面的时候,总是会默认先执行 setCurrentTab(0); 这就是为什么Tabhost总是会先默认加载第一个页面的原因。
找到问题就好办了,我们可以在tabHost.addTab(spec);方法之前,通过反射机制对Tabhost的变量 mCurrentTab进行赋值,具体代码如下:
Field mCurrentTab = null;
try {
mCurrentTab = tabHost.getClass()
.getDeclaredField("mCurrentTab");
mCurrentTab.setAccessible(true);
mCurrentTab.setInt(tabHost, -2);
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
// tabActivity实施了跳转界面
intent = new Intent().setClass(this, AActivity.class);
spec = tabHost.newTabSpec("A").setIndicator(disCoverTab).setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, BActivity.class);
spec = tabHost.newTabSpec("B").setIndicator(experienceTab).setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, CActivity.class);
spec = tabHost.newTabSpec("C").setIndicator(homeTab).setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, DActivity.class);
spec = tabHost.newTabSpec("D").setIndicator(tab3).setContent(intent);
tabHost.addTab(spec);
try {
if (mtabIndex == 0) {
mCurrentTab.setInt(tabHost, 1);
}
else {
mCurrentTab.setInt(tabHost, 0);
}
}
catch (Exception e){
e.printStackTrace();
}
tabHost.setCurrentTab(mtabIndex); //设置默认显示界面