Android实现驾考宝典做题翻页效果
效果如图所示:
思路:
a.利用ViewPager自带的动画效果,略作修改,实现滑动覆盖翻页效果。
b.移动时加入阴影效果。
1.关键代码如下所示:
public class ReaderViewPager extends ViewPager {
public ReaderViewPager(Context context) {
this(context, null);
}
public ReaderViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
setReadEffect();
setScrollerDuration();
}
private void setScrollerDuration() {
try {
Field field = ViewPager.class.getDeclaredField("mScroller");
field.setAccessible(true);
FixedSpeedScroller scroller = new FixedSpeedScroller(getContext(),
new DecelerateInterpolator());
field.set(this, scroller);
scroller.setmDuration(300);
} catch (Exception e) {
Log.e("@", "", e);
}
}
public void setReadEffect() {
setPageTransformer(true, new PageTransformer() {
private static final float MIN_SCALE = 0.75f;
@Override
public void transformPage(View view, float position) {
int pageWidth = view.getWidth();
int pageHeight =view.getHeight();
if (position < -1) { // [-Infinity,-1)
// This page is way off-screen to the left.
view.setAlpha(0);
} else if (position <= 0) { // [-1,0]
// Use the default slide transition when moving to the left page
view.setAlpha(1);
view.setTranslationX(0);
view.setScaleX(1);
view.setScaleY(1);
} else if (position <= 1) { // (0,1]
// Fade the page out.
// view.setAlpha(1 - position);
//
// // Counteract the default slide transition
view.setAlpha(1);
view.setTranslationX(pageWidth * -position);
//
// // Scale the page down (between MIN_SCALE and 1)
// float scaleFactor = MIN_SCALE
// + (1 - MIN_SCALE) * (1 - Math.abs(position));
// view.setScaleX(scaleFactor);
// view.setScaleY(scaleFactor);
} else { // (1,+Infinity]
// This page is way off-screen to the right.
view.setAlpha(0);
}
}
});
}
}
2.阴影效果添加(其实阴影是一张图片,本来是要在ReadViewPager内部添加阴影效果,但是不显示,貌似被ReadViewPage自己遮住了,就用笨办法实现了_):
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.zhangyipeng.anwerdemo.view.ReaderViewPager
android:id="@+id/readerViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!--阴影-->
<ImageView
android:id="@+id/shadowView"
android:layout_width="20dp"
android:layout_height="match_parent"
android:background="@mipmap/shadow_right"/>
</FrameLayout>
3.阴影随翻页而移动效果实现
readerViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
shadowView.setTranslationX(readerViewPager.getWidth()-positionOffsetPixels);
}
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
4.OK,就是这么简单,快去做一个自己的驾考宝典吧 。。。
5.我自己写了一些简单的实现方法,有3个View的实现方式,还有其他使用开源控件实现的
源码地址:
https://github.com/zzyyppqq/AnswerEffect
到这里就结束啦。
评论