How do I synchronize scrollview positions of dynamic horizontal scroll views inside a container?

后端 未结 1 1164
庸人自扰
庸人自扰 2020-12-12 06:22

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 re

相关标签:
1条回答
  • 2020-12-12 07:02

    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:

    0 讨论(0)
提交回复
热议问题