TabSpec spec = mTabHost.newTabSpec(tag)
.setIndicator(tabView)
.setContent(new TabContentFactory() {
public View createTabContent(String tag) { return view; } // 僅返回 View,生命周期不受管理
});
TabContentFactory 僅返回 View,**不觸發 Activity 生命周期**(onCreate/onResume 等),導致內容頁面邏輯無法執行。
// 繼承 TabActivity (已棄用) 或 FragmentActivity + FragmentTabHost (推薦)
// 這裡展示 TabActivity 時代的標準用法
public class CustomTabActivity extends TabActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_layout);
TabHost tabHost = getTabHost();
// Tab 1
Intent intent1 = new Intent(this, Tab1Activity.class);
TabHost.TabSpec spec1 = tabHost.newTabSpec("tab1")
.setIndicator(createTabView("Tab 1"))
.setContent(intent1); // 關鍵:Intent 啟動 Activity
tabHost.addTab(spec1);
// Tab 2
Intent intent2 = new Intent(this, Tab2Activity.class);
TabHost.TabSpec spec2 = tabHost.newTabSpec("tab2")
.setIndicator(createTabView("Tab 2"))
.setContent(intent2);
tabHost.addTab(spec2);
}
private View createTabView(String title) {
View view = LayoutInflater.from(this).inflate(R.layout.tab_indicator, null);
TextView tv = view.findViewById(R.id.tab_title);
tv.setText(title);
return view;
}
}
TabActivity 已棄用 (API 13)。現代項目使用:
// 佈局
// Activity
ViewPager2 viewPager = findViewById(R.id.viewPager);
TabLayout tabLayout = findViewById(R.id.tabLayout);
viewPager.setAdapter(new FragmentStateAdapter(this) {
@NonNull
@Override
public Fragment createFragment(int position) {
switch (position) {
case 0: return new Tab1Fragment();
case 1: return new Tab2Fragment();
default: return new Tab1Fragment();
}
}
@Override
public int getItemCount() { return 2; }
});
new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> {
tab.setText(position == 0 ? "Tab 1" : "Tab 2");
}).attach();
TabHost 時代:setContent(Intent) 關聯 Activity,獲得完整生命周期。TabContentFactory 僅返回 View,**不適用於包含業務邏輯的頁面**。