page.setAlpha(1);
page.setTranslationX(0);
page.setScaleX(1);
page.setScaleY(1);
} else if (position <= 1) { // (0,1]
// Fade the page out.
page.setAlpha(1 - position);
// Counteract the default slide transition
page.setTranslationX(pageWidth * -position);
page.setTranslationY(0);
// Scale the page down (between MIN_SCALE and 1)
float scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (1 - Math.abs(position));
page.setScaleX(scaleFactor);
page.setScaleY(scaleFactor);
} else { // (1,+Infinity]
// This page is way off-screen to the right.
page.setAlpha(0);
}
}
}
}
/**
- 交换x轴和y轴的移动距离
- @param event 获取事件类型的封装类MotionEvent
*/
private MotionEvent swapXY(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;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
mRecentTouchTime = System.currentTimeMillis();
if (getCurrentItem() == 0 && getChildCount() == 0) {
return false;
}
if (isVertical) {
boolean intercepted = super.onInterceptTouchEvent(swapXY(ev));
swapXY(ev);
// return touch coordinates to original reference frame for any child views
return intercepted;
} else {
return super.onInterceptTouchEvent(ev);
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (getCurrentItem() == 0 && getChildCount() == 0) {
return false;
}
if (isVertical) {
return super.onTouchEvent(swapXY(ev));
} else {
return super.onTouchEvent(ev);
}
}
}
3.2 ViewPager和Fragment
- 采用了ViewPager+FragmentStatePagerAdapter+Fragment来处理。为何选择使用FragmentStatePagerAdapter,主要是因为使用 FragmentStatePagerAdapter更省内存,但是销毁后新建也是需要时间的。一般情况下,如果你是用于ViewPager展示数量特别多的条目时,那么建议使用FragmentStatePagerAdapter。关于PagerAdapter的深度解析,可以我这篇文章:PagerAdapter深度解析和实践优化
- 在activity中的代码如下所示
private void initViewPager() {
List list = new ArrayList<>();
ArrayList fragments = new ArrayList<>();
for (int a = 0; a< DataProvider.VideoPlayerList.length ; a++){
Video video = new Video(DataProvider.VideoPlayerTitle[a],
10,“”,DataProvider.VideoPlayerList[a]);
list.add(video);
fragments.add(VideoFragment.newInstant(DataProvider.VideoPlayerList[a]));
}
vp.setOffscreenPageLimit(1);
vp.setCurrentItem(0);
vp.setOrientation(DirectionalViewPager.VERTICAL);
FragmentManager supportFragmentManager = getSupportFragmentManager();
MyPagerAdapter myPagerAdapter = new MyPagerAdapter(fragments, supportFragmentManager);
vp.setAdapter(myPagerAdapt