Search code examples
javaandroidhorizontalscrollviewsmooth-scrolling

How to center views with a smooth scroll in an horizontalScrollView


I am trying to center a view with a smooth scroll in an horizontalScrollView, when the element/view is clicked/tabbed.

Here's my latest attempt to achieve this.

Code:

public void scrollCenterBarItem(DrinkCategoryView toBarItem) {
    int endPos    = (int) toBarItem.getView().getX();
    int halfWidth = (int) toBarItem.getView().getWidth() / 2;

    barsScroller.smoothScrollTo(endPos + halfWidth, 0);
}

I don't find it neccesary to include all the code, but DrinkCategoryView is a class where the items views of the horizontalScrollView are located. the variable called barsScroller is the horizontalScrollView.

And here is the xml part where the horizontalScrollView and linearlayout, containing the views is:

        <HorizontalScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/bars_scroller"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:scrollbars="none">
            <LinearLayout
                android:id="@+id/drinksCategoryList"
                android:orientation="horizontal"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </HorizontalScrollView>
    </RelativeLayout>

And here is the item xml layout of the HorizontalScrollView:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/drinkCategoryItem">


    <com.ivankocijan.magicviews.views.MagicTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/drinkCategoryItemTextView"
        android:textSize="18sp"
        app:typeFace="@string/opensans_regular"
        android:textColor="@color/black"
        android:padding="16dp" />
</LinearLayout>

I hope you can understand what i am trying to achieve and maybe help me in the right direction.

Any help will be greatly appreciated.


Solution

  • Try something like this:

    public void scrollCenterBarItem(DrinkCategoryView toBarItem) {
        int endPos    = (int) toBarItem.getView().getX();
        int halfWidth = (int) toBarItem.getView().getWidth() / 2;
    
        barsScroller.smoothScrollTo(endPos + halfWidth - barScroller.getWidth() / 2, 0);
    }
    

    If this still not working, you may want to post your failed test result in the form of images.