我有类似的情况,但似乎没有一个答案有帮助。所以,我在这里发布我的解决方案:
// tab selection history, each tab has a tag which is a string
private List<String> tabIdHistory = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstance) {
super.onCreate(savedInstanceState);
// this layout contains TabHost and TabWidget
setContentView(R.layout.activity_main);
TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost);
tabHost.setup();
tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
@Override
public void onTabChanged(String tabId) {
tabIdHistory.remove(tabId); // ensure uniqueness
tabIdHistory.add(tabId);
}
});
// continue your tab initialisation, such as
// tabHost.addTab(tabHost.newTabSpec(TAG)
// .setContent(...).setIndicator(...));
}
@Override
public void onBackPressed() {
if (tabIdHistory.size() > 1) {
// pop the current last item, we want the second last
tabIdHistory.remove(tabIdHistory.size() - 1);
tabHost.setCurrentTabByTag(tabIdHistory.get(tabIdHistory.size() - 1));
} else {
super.onBackPressed();
}
}
如果使用 select tab#1, tab#3, tab#2, tab#1,则返回堆栈为“3, 2, 1”,如果用户按返回按钮 3 次,应用程序将退出到主屏幕。如果要保留完整的历史记录,请注释掉这一行:
tabIdHistory.remove(tabId);