th = this.getTabHost();
int tadid = 2;
// 设置mCurrentTab为非-1,addtab时候不会进入setCurrentTab()
try {
Field idcurrent = th.getClass().getDeclaredField("mCurrentTab");
idcurrent.setAccessible(true);
idcurrent.setInt(th, -2);
} catch (Exception e) {
e.printStackTrace();
}
th.addTab(th.newTabSpec("myview1").setIndicator("myview111").setContent(new Intent(this, MyView1.class)));
th.addTab(th.newTabSpec("myview2").setIndicator("myview222").setContent(new Intent(this, MyView2.class)));
th.addTab(th.newTabSpec("myview3").setIndicator("myview333").setContent(new Intent(this, MyView3.class)));
// 设置mCurrentTab与tadid不同,并且不能数组越界(0-2),保证第一次进入tab的setCurrentTab()方法正常运行
try {
Field idcurrent = th.getClass().getDeclaredField("mCurrentTab");
idcurrent.setAccessible(true);
if (tadid == 0) {
idcurrent.setInt(th, 1);
} else {
idcurrent.setInt(th, 0);
}
} catch (Exception e) {
e.printStackTrace();
}
th.setCurrentTab(tadid);
在我们使用TabHost 的时候,如果我们希望默认进入非第一个选项卡的时候,我们会这样写:tabHost.setCurrentTab(???);,但是,这样就出现了一个问题。我们发现无论进入哪个选项卡,在第一次进入TabHost的时候,都会调用第一个选项卡的 OnCreate方法! 这个不是我们想要的。 加上上面两个写注释的方法,即可解决问题!