Monday, June 25, 2012

Center Tab Item in TabWidget and HorizontalScrollView in Android

So you have a TabWidget within HorizontalScrollView, and you want to center the selectedTab (either dynamically or if you have ViewPager on page scroll). On your TabHost, you'll have something like this.
<HorizontalScrollView
        android:id="@+id/horizontalScrollView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:fillViewport="true"
        android:scrollbars="none"
        android:layout_weight="0"
        >

    <TabWidget
            android:id="@android:id/tabs"
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            />
</HorizontalScrollView>

On your activity/fragment
public void centerTabItem(int position) {
    tabHost.setCurrentTab(position);
    final TabWidget tabWidget = tabHost.getTabWidget();
    final int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
    final int leftX = tabWidget.getChildAt(position).getLeft();
    int newX = 0;

    newX = leftX + (tabWidget.getChildAt(position).getWidth() / 2) - (screenWidth / 2);
    if (newX < 0) {
        newX = 0;
    }
    horizontalScrollView.scrollTo(newX, 0);
}

Say you have a viewPager, then you could use it like
public void onPageSelected(int position) {
    centerTabItem(position);
}
Explanation
final int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
Get the phone's width, we need to to know where the center is (by dividing it by half)

final int leftX = tabWidget.getChildAt(position).getLeft();
Get the x position of the item we want to center, this is relative to its parent (horizontalScrollView)

newX = leftX + (tabWidget.getChildAt(position).getWidth() / 2) - (screenWidth / 2);
The center would be calculated based on horizontalScrollView.scrollTo, so the left x plus half the item width, would be negative value as the new x would scroll to the left of the parent, then if you minus (or plus since its going to the left plane/negative) to the half width value of the device then you will arrive in the center.

horizontalScrollView.scrollTo(newX, 0);
Scroll the tabWidget to the newX, y stays at 0
Hope this helps :)
Post a Comment