我在 HorizontalScrollView 中有一个 TabHost,有时可以有超过 20 个选项卡。在每个选项卡活动上,我都可以按下“下一步”按钮,指示 TabHost 移动到下一个选项卡。问题是,如果 Scrollview 不在屏幕上,我无法让 Scrollview 滚动到选定的选项卡。
有人可以告诉我如何做到这一点吗?
我在 HorizontalScrollView 中有一个 TabHost,有时可以有超过 20 个选项卡。在每个选项卡活动上,我都可以按下“下一步”按钮,指示 TabHost 移动到下一个选项卡。问题是,如果 Scrollview 不在屏幕上,我无法让 Scrollview 滚动到选定的选项卡。
有人可以告诉我如何做到这一点吗?
您必须将 xml 中的 TabWidget“包装”到 HorizontalScrollView 中:
……
<HorizontalScrollView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:fillViewport="true"
android:scrollbars="none"
android:id="@+id/tabsHorizontalScrollView">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0"/>
</HorizontalScrollView>
……
并设置为 TabHost TabHost.OnTabChangeListener
@Override
public void onTabChanged(final String tag) {
View tabView = tabHost.getCurrentTabView();
int scrollPos = tabView.getLeft() - (tabsHorizontalScrollView.getWidth() - tabView.getWidth()) / 2;
tabsHorizontalScrollView.smoothScrollTo(scrollPos, 0);
}
此处描述了更好、更流畅的方法:https ://stackoverflow.com/a/6131550/2511775
在设置选项卡时执行此操作:
for (int i = 0; i < count; i++) {
getTabWidget().getChildAt(i).setFocusableInTouchMode(true);
}
有一个可行的解决方案:
@Override
public void onTabChanged(final String tag) {
final int pos = this.mTabHost.getCurrentTab();
final View tabView = mTabHost.getTabWidget().getChildTabViewAt(pos);
final int[] locationOnScreen= new int[2];
tabView.getLocationOnScreen(locationOnScreen);
mtabsHorizontalScrollView.scrollTo(locationOnScreen[0], 0);
}