I want to move a view when the ViewPager scrolls. I found scroll listener in view pager, with the parameter positionOffset, which I use to adjust the left margin of the view I want to move.
It works, but the scrolling isn’t smooth anymore. If I comment the scroll listener out, it’s smooth again. The view I’m animating is super simple – only a small square with a plain color. The requestLayout() call is done only on this view. The code:
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (positionOffset != 0 || (positionOffset == 0 && position == 0)) {
pars.leftMargin = (int)(scrollablePart * positionOffset);
tabBG.requestLayout();
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
I don’t know what’s the problem, I have other place with a view which I animate in a similar way (adjusting margins, according to a -not pager-slider) and it’s smooth. I also have seen an app where the positions of some views are adjusted dynamically according to the scrolling of a pager, and it’s very smooth.
Any idea? Thanks in advance!
Any animation that involves
requestLayout()will be slow. If all you are trying to do is move a View around, use aTranslateAnimation, orView.offsetLeftAndRight()orView.setTranslationX(), etc. Do not userequestLayout()or anything layout related.