Skip to content Skip to sidebar Skip to footer

How To Synchronize Viewpager With Horizontalscrollview To Keep Them Moving Together

I have a ViewPager and a HorizontalScrollView. I would to move HorizontalScrollView in the same position of ViewPager, programmatically, so I would they behave in this way: when I

Solution 1:

I solved in this way, not so elegant and accurate, but it works. Since I've not found a way to get smoothScrollTo working, I tried using smoothScrollBy, that is a bit different from the first because it scrolls the horizontalScrollView by a certain number of pixels. So, i.e. if we know that the width of every item of our horizontalScrollView is about 72dp, we can convert dp to pixels programmatically and finally call smoothScrollBy. You have also to save the previous position of the last page in order to give the right direction to scroll the horizontalScrollView. Here I show how I have modified the OnPageSelected method (precPos is an Integer initialized to 0):

@OverridepublicvoidonPageSelected(finalint position) {
        //hscroll.smoothScrollTo(position, 0);
        hscroll.setSmoothScrollingEnabled(true);

        // convert dp to pixelsResourcesr= getResources();
        floatpx= TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 72, r.getDisplayMetrics());

        // and found the right direction to scrollif (position < precPos) hscroll.smoothScrollBy((int) -px, 0);
        else hscroll.smoothScrollBy((int) px, 0);
        // save the last position
        precPos = position;
}

I hope this helps if you're facing the same problem. So, I solved in this way, anyway if someone could explain me how I would use smoothScrollTo, you're welcome :)

Post a Comment for "How To Synchronize Viewpager With Horizontalscrollview To Keep Them Moving Together"