The easiest way to do that is to:
- Remove backgrounds from
Fragments
in the ViewPager
(I assume you use Fragments
inside your ViewPager's
Adapter
... if not, let me know). And by "remove background" I mean e.g. set it to "@android:color/transparent"
.
- Remove background from the
ViewPager
itself (also e.g. with setting it's color to transparent
).
- Put a
View
that will act as a changing background below (z-wise) your ViewPager
. For example like this (without parameters):
<FrameLayout>
<View android:id="@+id/animated_color_view"/>
<android.support.v4.view.ViewPager/>
</FrameLayout>
- Create a way to animate background color of the
animated_color_view
. You can use one of the ways included in the thread linked by REG1 in the comment (edit: the comment has been deleted, but this link points to the same thread). For example like this (the approach was taken from this post):
int[] pageColors = new int[]{Color.RED, Color.GREEN};
int currentColor = pageColors[0];
ValueAnimator colorAnimation;
public void animateToColor(int colorTo) {
if (colorAnimation != null) {
colorAnimation.cancel();
}
colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), currentColor, colorTo);
colorAnimation.setDuration(250); // milliseconds
colorAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animator) {
currentColor = (int) animator.getAnimatedValue();
animatedColorView.setBackgroundColor(currentColor);
}
});
colorAnimation.start();
}
- Add an
OnPageChangeListener
that will call this animating method every time a page is selected.
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
animateToColor(pageColors[position]);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
And a little side-note: remember the pageColors
array's size must be equal to the number of pages in your ViewPager
.