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

interface LobbyReservationHSVListener{
        void updateScrollPosition(int scrollX);
    }

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

public class HorizontalActivity extends AppCompatActivity implements
        LobbyReservationHSVListener {

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

    @Override
    public void updateScrollPosition(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,new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                for(int i=0; i<container.getChildCount();i++){
                    HorizontalScrollView hsv = 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.

public class LobbyReservationRowView extends FrameLayout implements
        OnClickListener, OnItemClickListener, HorizontalScrollView.OnScrollChangeListener {

    private LobbyReservationHSVListener hsvUpdateListener;

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

    public void setHSVUpdateListener(LobbyReservationHSVListener hsvUpdateListener){
        this.hsvUpdateListener = hsvUpdateListener;
    }

 @Override
    public void onScrollChange(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?"