Skip to content Skip to sidebar Skip to footer

How Do I Synchronize Scrollview Positions Of Dynamic Horizontal Scroll Views Inside A Container?

I have a parent container in one of my activities which make a call to it's child containers consisting of a horizontal scrollview as one of the objects. Sort of like a recyclervi

Solution 1:

You can achieve the synchronized scrolling with LiveData from Android Architecture Components. Declare an interface

interfaceLobbyReservationHSVListener{
        voidupdateScrollPosition(int scrollX);
    }

Declare a MutableLiveData variable and implement the LobbyReservationHSVListener in your activity like below:

publicclassHorizontalActivityextendsAppCompatActivityimplementsLobbyReservationHSVListener {

    MutableLiveData<Integer> hsvPosition = newMutableLiveData<Integer>();

    @OverridepublicvoidupdateScrollPosition(int scrollX) {
        hsvPosition.setValue(scrollX);
    }
}

In onCreate in your activity start observing the MutableLiveData you declared. Whenever its value changes, loop through all children views of container and update their scroll positions.

hsvPosition.observe(this,newObserver<Integer>() {
            @OverridepublicvoidonChanged(Integer integer) {
                for(int i=0; i<container.getChildCount();i++){
                    HorizontalScrollViewhsv= container.getChildAt(i).findViewById(R.id.horizontal_timebar_view);
                    hsv.smoothScrollTo(integer,0);
                }
            }
        });

In your LobbyReservationRowView create a function to set the LobbyReservationHSVListener object and call updateScrollPosition whenever scroll changes.

publicclassLobbyReservationRowViewextendsFrameLayoutimplementsOnClickListener, OnItemClickListener, HorizontalScrollView.OnScrollChangeListener {

    private LobbyReservationHSVListener hsvUpdateListener;

    @BindView(R.id.horizontal_timebar_view)
    HorizontalScrollView mHorizontalTimeBarView;

    publicvoidsetHSVUpdateListener(LobbyReservationHSVListener hsvUpdateListener){
        this.hsvUpdateListener = hsvUpdateListener;
    }

 @OverridepublicvoidonScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

        hsvUpdateListener.updateScrollPosition(scrollX);
    }

}

Don't forget to call setHSVUpdateListener(this) on your LobbyReservationRowView object whenever adding it to your container

You should get something like this:

enter image description here

Post a Comment for "How Do I Synchronize Scrollview Positions Of Dynamic Horizontal Scroll Views Inside A Container?"