フラグメントを簡単に切り替えるために、次のように HorizontalScrollView をタブ レイアウトに埋め込みます。
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fillViewport="true"
android:scrollbars="none" >
<TabWidget android:id="@android:id/tabs"
android:layout_height="wrap_content"
android:layout_width="wrap_content">
</TabWidget>
</HorizontalScrollView>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</TabHost>
しかし、コードにフラグメントを追加した後 (以下に示す)、HorizontalScrollView の最後に余分な空白が突然表示されます。
スクロール前
スクロール後
コードは非常に複雑ですが、重要な部分を示します。
{
mTabHost = (TabHost) childLayout.findViewById(android.R.id.tabhost);
mTabHost.setup();
FrameLayout tabsFL = (FrameLayout) childLayout.findViewById(android.R.id.tabcontent);
tabsFL.setId(TABS_FRAME_ID);
for (int i = 0; i < list.size(); i++) {
mTabHost.addTab(newTab(String.valueOf(i), list.get(i).getTitle(), tabsFL.getId()));
}
mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
@Override
public void onTabChanged(String tabId) {
updateTab(tabId, Integer.parseInt(tabId), list);
}
});
//manually load first fragment
mTabHost.setCurrentTab(mCurrentTab);
updateTab(String.valueOf(mCurrentTab), mCurrentTab, list);
}
private TabSpec newTab(String tag, String tabLabel, int tabContentId) {
int count = Integer.parseInt(tag);
count +=1;
View indicator = inflater.inflate(R.layout.details_tab,
(ViewGroup) childLayout.findViewById(android.R.id.tabs), false);
((TextView) indicator.findViewById(R.id.text)).setText(count + ". " + tabLabel);
TabSpec tabSpec = mTabHost.newTabSpec(tag);
tabSpec.setIndicator(indicator);
tabSpec.setContent(tabContentId);
return tabSpec;
}
private void updateTab(String tabId, int id, ArrayList<CustomObject> frags) {
mCurrentTab = id;
FragmentManager fm = activity.getSupportFragmentManager();
fm.beginTransaction()
.replace(TABS_FRAME_ID, DetailsFragment.newInstance(frags.get(id)), tabId)
.commitAllowingStateLoss();
}
これも無関係ですが、最初のタブが手動で読み込まれないという問題もあります (タブをクリックするとフラグメントが完全に読み込まれますが、最初のタブだけが何らかの理由で読み込まれません)。