Jr G.
Jr G.

Reputation: 87

TabHost in ScrollView, scroll to tab when selected

I have a TabHost inside a HorizontalScrollView that can sometimes have more than 20 tabs. On every tab activity, I can press a "next" button that instructs the TabHost to move to the next tab. The problem is, I cannot get the Scrollview to scroll to a selected tab if it is off screen.

Could someone tell me how this can be done?

Upvotes: 2

Views: 3837

Answers (3)

Vania Diezel
Vania Diezel

Reputation: 77

you must "wrap" TabWidget in xml into 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>

....

and set to 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);
}

Upvotes: 3

Ashkan Sarlak
Ashkan Sarlak

Reputation: 7344

Better and smoother way of doing this is described here: https://stackoverflow.com/a/6131550/2511775

Do this for when you setup your tabs:

for (int i = 0; i < count; i++) {
    getTabWidget().getChildAt(i).setFocusableInTouchMode(true);
}

Upvotes: 1

android developer
android developer

Reputation: 116322

got a working solution :

@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);
}

Upvotes: 1

Related Questions