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 :)
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 usingsmoothScrollBy
, 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 about72dp
, we can convert dp to pixels programmatically and finally callsmoothScrollBy
. 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 theOnPageSelected
method (precPos
is an Integer initialized to 0):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 :)