在 Android TabHost 中,直接對 TabHost 設置 OnLongClickListener 無法區分具體哪個 Tab 被長按。需對單個 Tab 視圖 (TabSpec 對應的 View) 設置監聽器。
TabHost tabHost = getTabHost();
tabHost.setOnLongClickListener(new OnLongClickListener() { ... });
// 錯誤:監聽整個 TabHost,無法區分具體 Tab
TabHost tabHost = getTabHost();
// 添加 Tab 後...
tabHost.addTab(spec1);
tabHost.addTab(spec2);
// 針對每個 Tab 視圖設置長按監聽
for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
final int tabIndex = i;
View tabView = tabHost.getTabWidget().getChildAt(i);
tabView.setOnLongClickListener(v -> {
// 處理第 tabIndex 個 Tab 的長按
if (tabIndex == 0) {
startActivity(new Intent(this, LongClickActivity1.class));
} else if (tabIndex == 1) {
startActivity(new Intent(this, LongClickActivity2.class));
}
return true; // 消費事件
});
// 可選:同時保留點擊切換功能
tabView.setOnClickListener(v -> tabHost.setCurrentTab(tabIndex));
}
// 自定義 Tab 視圖 res/layout/custom_tab.xml
<TextView xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@android:id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="12dp"
android:textSize="14sp" />
// 代碼中
TabHost.TabSpec spec = tabHost.newTabSpec("tab1");
View tabIndicator = LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
TextView title = tabIndicator.findViewById(android.R.id.title);
title.setText("Tab 1");
// 直接在自定義視圖上設置監聽
tabIndicator.setOnLongClickListener(v -> {
// 處理長按
return true;
});
spec.setIndicator(tabIndicator).setContent(intent);
tabHost.addTab(spec);
| 方法 | 說明 |
|---|---|
| tabHost.getTabWidget() | 獲取包含所有 Tab 按鈕的 TabWidget |
| getChildAt(index) | 獲取指定索引的 Tab 視圖 (View) |
| getChildCount() | 獲取 Tab 總數 |
| View.setOnLongClickListener | 設置視圖長按監聽 |
TabLayout tabLayout = findViewById(R.id.tabLayout);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
// ... 其他回調
});
// 長按監聽 (需自定義 Tab 視圖)
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
View customView = tab.getCustomView(); // 或 tab.view (內部)
if (customView != null) {
customView.setOnLongClickListener(v -> {
// 處理長按
return true;
});
}
}
TabHost 已棄用,新專案請使用 ViewPager2 + TabLayouttrue 消費長按事件可防止觸發點擊