这里说的是ViewPager在页面切换的时候更改Item的样式:缩放、位置变化等等;本文罗列三种情况,具体如下:
1. 所有Item重叠,滑动时透明度变化,X、Y拉伸
代码如下:
public class PageTransformerOne implements ViewPager.PageTransformer {
private static float MIN_SCALE = 0.75f;
@SuppressLint("NewApi")
@Override
public void transformPage(View view, float position) {
int pageWidth = view.getWidth();
if (position < -1) {
view.setAlpha(0);
} else if (position <= 0) {
view.setAlpha(1);
view.setTranslationX(0);
view.setScaleX(1);
view.setScaleY(1);
} else if (position <= 1) {
view.setAlpha(1 - position);
view.setTranslationX(pageWidth * -position);
float scaleFactor = MIN_SCALE + (1 - MIN_SCALE)
* (1 - Math.abs(position));
view.setScaleX(scaleFactor);
view.setScaleY(scaleFactor);
} else {
view.setAlpha(0);
}
}
}
运行效果:
2. 所有Item横向排列,滑动时透明度变化,X、Y拉伸
代码如下:
public class PageTransformerTwo implements ViewPager.PageTransformer {
private static float MIN_SCALE = 0.85f;
private static float MIN_ALPHA = 0.5f;
@Override
public void transformPage(View view, float position) {
int pageWidth = view.getWidth();
int pageHeight = view.getHeight();
if (position < -1) {
view.setAlpha(0);
} else if (position <= 1) {
float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
float vertMargin = pageHeight * (1 - scaleFactor) / 2;
float horzMargin = pageWidth * (1 - scaleFactor) / 2;
if (position < 0) {
view.setTranslationX(horzMargin - vertMargin / 2);
} else {
view.setTranslationX(-horzMargin + vertMargin / 2);
}
view.setScaleX(scaleFactor);
view.setScaleY(scaleFactor);
view.setAlpha(MIN_ALPHA + (scaleFactor - MIN_SCALE)
/ (1 - MIN_SCALE) * (1 - MIN_ALPHA));
} else {
view.setAlpha(0);
}
}
}
滑动效果:
3. (类似于画廊的效果)所有Item横向排列,滑动时透明度变化,X、Y拉伸
public class PageTransformerThree implements ViewPager.PageTransformer {
private float MIN_SCALE = 0.5f;
@SuppressLint("NewApi")
public void transformPage(View view, float position) {
int pageWidth = view.getWidth();
Log.d("123",position+" viewpager");
if (position < -1) {
position = -1;
} else if (position > 1) {
position = 1;
}
view.setTranslationX(0);
float scaleFactor = MIN_SCALE + (1 - MIN_SCALE)
* (1 - Math.abs(position));
view.setScaleX(scaleFactor);
view.setScaleY(scaleFactor);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
view.getParent().requestLayout();
}
}
}
滑动效果,也可以在屏幕上同时显示多个: