How to synchronize ViewPager with HorizontalScroll

2019-09-11 09:07发布

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 scroll ViewPager to page 1, HorizontalScrollView moves automatically to position 1. I've tried using ViewPager.OnPageChangeListener and smoothScrollTo (int x, int y), but I don't understand how to use the last method: in particularly, I don't understand what does it mean X and Y in this case. Here the code:

public class MyClass extends AppCompatActivity implements ViewPager.OnPageChangeListener {

    ViewPager viewPager;
    HorizontalScrollView hscroll;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ...

        viewPager = (ViewPager) findViewById(R.id.pager);
        hscroll = (HorizontalScrollView) findViewById(R.id.horizontalScrollView);
        viewPager.setOnPageChangeListener(this);

        ...

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        hscroll.smoothScrollTo(position-1, position);
        Toast.makeText(getApplicationContext(), String.valueOf(position), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

Any idea? Every help would be greatly appreciated, thanks in advance :)

1条回答
你好瞎i
2楼-- · 2019-09-11 09:22

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):

@Override
    public void onPageSelected(final int position) {
        //hscroll.smoothScrollTo(position, 0);
        hscroll.setSmoothScrollingEnabled(true);

        // convert dp to pixels
        Resources r = getResources();
        float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 72, r.getDisplayMetrics());

        // and found the right direction to scroll
        if (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 :)

查看更多
登录 后发表回答