VerticalViewPager
/**
* 垂直滑动的ViewPager
*/
public class VerticalViewPager extends ViewPager {
public VerticalViewPager(Context context) {
this(context, null);
}
public VerticalViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
//设置viewpage的切换动画,这里设置才能真正实现垂直滑动的viewpager
setPageTransformer(true, new DefaultTransformer());
}
/**
* 拦截touch事件
*
*/
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
boolean intercept = super.onInterceptTouchEvent(swapEvent(ev));
swapEvent(ev);
return intercept;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
return super.onTouchEvent(swapEvent(ev));
}
private MotionEvent swapEvent(MotionEvent event) {
//获取宽高
float width = getWidth();
float height = getHeight();
//将Y轴的移动距离转变成X轴的移动距离
float swappedX = (event.getY() / height) * width;
//将X轴的移动距离转变成Y轴的移动距离
float swappedY = (event.getX() / width) * height;
//重设event的位置
event.setLocation(swappedX, swappedY);
return event;
}
}
自定义viewpager切换动画
public class DefaultTransformer implements ViewPager.PageTransformer {
public static final String TAG = "simple";
@Override
public void transformPage(View view, float position) {
float alpha = 0;
if (0 <= position && position <= 1) {
alpha = 1 - position;
} else if (-1 < position && position < 0) {
alpha = position + 1;
}
view.setAlpha(alpha);
float transX = view.getWidth() * -position;
view.setTranslationX(transX);
float transY = position * view.getHeight();
view.setTranslationY(transY);
}
}
不设置切换动画,还会是水平方向的动画,像这种