android自己定义ViewPager之——3D效果应用

 今天在github里看到一个3D效果的ViewPager,感觉做出来的ViewPager滑动的时候效果十分的炫,就check out下来研究了一下怎样实现的。以及怎样使用。将整个ViewPager稍加改动后(主要是处理了一下与项目中其他控滑动控件的事件冲突)后。应用到了自己如今项目中。感觉这个效果真的很的不错。如今把自己写的一个Demo分享出来。

 以下是这个ViewPager嵌入到项目中的效果图:

 

改动以后。在切换ViewPager时会有立体感。会为自己的应用增色不少。以下把使用的Demo发出来。事实上与使用普通的ViewPager全然一样。仅仅只是好像仅仅能用PagerAdapter及其子类Adapter为它填充数据。

1.ViewPager3D源代码:

public class ViewPager3D extends ViewPager
{
	/**
	 * maximum overscroll rotation of the children is 90 divided by this value
	 */
	final static float DEFAULT_OVERSCROLL_ROTATION = 2f;

	/**
	 * maximum z distance to translate child view
	 */
	final static int DEFAULT_OVERSCROLL_TRANSLATION = 150;

	/**
	 * maximum z distanze during swipe
	 */
	final static int DEFAULT_SWIPE_TRANSLATION = 100;

	/**
	 * maximum rotation during swipe is 90 divided by this value
	 */
	final static float DEFAULT_SWIPE_ROTATION = 3;

	/**
	 * duration of overscroll animation in ms
	 */
	final private static int DEFAULT_OVERSCROLL_ANIMATION_DURATION = 400;

	/**
	 * if true alpha of children gets animated during swipe and overscroll
	 */
	final private static boolean DEFAULT_ANIMATE_ALPHA = true;

	@SuppressWarnings("unused")
	private final static String DEBUG_TAG = ViewPager.class.getSimpleName();
	private final static int INVALID_POINTER_ID = -1;
	private final static double RADIANS = 180f / Math.PI;

	/**
	 * @author renard
	 */
	private class OverscrollEffect
	{
		private float mOverscroll;
		private Animator mAnimator;

		/**
		 * @param deltaDistance [0..1] 0->no overscroll, 1>full overscroll
		 */
		public void setPull(final float deltaDistance)
		{
			mOverscroll = deltaDistance;
			invalidateVisibleChilds();
		}

		/**
		 * called when finger is released. starts to animate back to default
		 * position
		 */
		private void onRelease()
		{
			if (mAnimator != null && mAnimator.isRunning())
			{
				mAnimator.addListener(new AnimatorListener()
				{

					@Override
					public void onAnimationStart(Animator animation)
					{
					}

					@Override
					public void onAnimationRepeat(Animator animation)
					{
					}

					@Override
					public void onAnimationEnd(Animator animation)
					{
						startAnimation(0);
					}

					@Override
					public void onAnimationCancel(Animator animation)
					{
					}
				});
				mAnimator.cancel();
			}
			else
			{
				startAnimation(0);
			}
		}

		private void startAnimation(final float target)
		{
			mAnimator = ObjectAnimator.ofFloat(this, "pull", mOverscroll, target);
			mAnimator.setInterpolator(new DecelerateInterpolator());
			final float scale = Math.abs(target - mOverscroll);
			mAnimator.setDuration((long) (mOverscrollAnimationDuration * scale));
			mAnimator.start();
		}

		private boolean isOverscrolling()
		{
			if (mScrollPosition == 0 && mOverscroll < 0)
			{
				return true;
			}
			if (getAdapter() != null)
			{
				final boolean isLast = (getAdapter().getCount() - 1) == mScrollPosition;
				if (isLast && mOverscroll > 0)
				{
					return true;
				}
			}
			return false;
		}

	}

	final private OverscrollEffect mOverscrollEffect = new OverscrollEffect();
	final private Camera mCamera = new Camera();

	private OnPageChangeListener mScrollListener;
	private float mLastMotionX;
	private int mActivePointerId;
	private int mScrollPosition;
	private float mScrollPositionOffset;
	private int mScrollPositionOffsetPixels;
	final private int mTouchSlop;

	private float mOverscrollRotation;
	private float mSwipeRotation;
	private int mOverscrollTranslation;
	private int mSwipeTranslation;
	private int mOverscrollAnimationDuration;
	private boolean mAnimateAlpha;
	private Rect mTempTect = new Rect();

	public ViewPager3D(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		setStaticTransformationsEnabled(true);
		final ViewConfiguration configuration = ViewConfiguration.get(context);
		mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
		super.setOnPageChangeListener(new MyOnPageChangeListener());
		init(attrs);
	}

	private void init(AttributeSet attrs)
	{
		TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ViewPager3D);
		mOverscrollRotation = a.getFloat(R.styleable.ViewPager3D_overscroll_rotation, DEFAULT_OVERSCROLL_ROTATION);
		mSwipeRotation = a.getFloat(R.styleable.ViewPager3D_swipe_rotation, DEFAULT_SWIPE_ROTATION);
		mSwipeTranslation = a.getInt(R.styleable.ViewPager3D_swipe_translation, DEFAULT_SWIPE_TRANSLATION);
		mOverscrollTranslation = a.getInt(R.styleable.ViewPager3D_overscroll_translation,
				DEFAULT_OVERSCROLL_TRANSLATION);
		mOverscrollAnimationDuration = a.getInt(R.styleable.ViewPager3D_overscroll_animation_duration,
				DEFAULT_OVERSCROLL_ANIMATION_DURATION);
		mAnimateAlpha = a.getBoolean(R.styleable.ViewPager3D_animate_alpha, DEFAULT_ANIMATE_ALPHA);
		a.recycle();
	}

	public boolean isAnimateAlpha()
	{
		return mAnimateAlpha;
	}

	public void setAnimateAlpha(boolean mAnimateAlpha)
	{
		this.mAnimateAlpha = mAnimateAlpha;
	}

	public int getOverscrollAnimationDuration()
	{
		return mOverscrollAnimationDuration;
	}

	public void setOverscrollAnimationDuration(int mOverscrollAnimationDuration)
	{
		this.mOverscrollAnimationDuration = mOverscrollAnimationDuration;
	}

	public int getSwipeTranslation()
	{
		return mSwipeTranslation;
	}

	public void setSwipeTranslation(int mSwipeTranslation)
	{
		this.mSwipeTranslation = mSwipeTranslation;
	}

	public int getOverscrollTranslation()
	{
		return mOverscrollTranslation;
	}

	public void setOverscrollTranslation(int mOverscrollTranslation)
	{
		this.mOverscrollTranslation = mOverscrollTranslation;
	}

	public float getSwipeRotation()
	{
		return mSwipeRotation;
	}

	public void setSwipeRotation(float mSwipeRotation)
	{
		this.mSwipeRotation = mSwipeRotation;
	}

	public float getOverscrollRotation()
	{
		return mOverscrollRotation;
	}

	public void setOverscrollRotation(float mOverscrollRotation)
	{
		this.mOverscrollRotation = mOverscrollRotation;
	}

	@Override
	public void setOnPageChangeListener(OnPageChangeListener listener)
	{
		mScrollListener = listener;
	}

	;

	private void invalidateVisibleChilds()
	{
		for (int i = 0; i < getChildCount(); i++)
		{
			final View childAt = getChildAt(i);
			childAt.getLocalVisibleRect(mTempTect);
			final int area = mTempTect.width() * mTempTect.height();
			if (area > 0)
			{
				childAt.invalidate();
			}
		}

		invalidate();
	}

	private class MyOnPageChangeListener implements OnPageChangeListener
	{

		@Override
		public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
		{
			if (mScrollListener != null)
			{
				mScrollListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
			}
			mScrollPosition = position;
			mScrollPositionOffset = positionOffset;
			mScrollPositionOffsetPixels = positionOffsetPixels;
			// Log.i(DEBUG_TAG, "mScrollPosition = " + position + " offset = " + String.format("%f.2", positionOffset));
			// Log.i(DEBUG_TAG, "onPageScrolled");

			invalidateVisibleChilds();
		}

		@Override
		public void onPageSelected(int position)
		{
			if (mScrollListener != null)
			{
				mScrollListener.onPageSelected(position);
			}
		}

		@Override
		public void onPageScrollStateChanged(final int state)
		{
			if (mScrollListener != null)
			{
				mScrollListener.onPageScrollStateChanged(state);
			}
			if (state == SCROLL_STATE_IDLE)
			{
				mScrollPositionOffset = 0;
			}
		}
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev)
	{
		final int action = ev.getAction() & MotionEventCompat.ACTION_MASK;
		switch (action)
		{
		case MotionEvent.ACTION_DOWN:
		{
			mLastMotionX = ev.getX();
			mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
			break;
		}
		case MotionEventCompat.ACTION_POINTER_DOWN:
		{
			final int index = MotionEventCompat.getActionIndex(ev);
			final float x = MotionEventCompat.getX(ev, index);
			mLastMotionX = x;
			mActivePointerId = MotionEventCompat.getPointerId(ev, index);
			break;
		}
		}
		return super.onInterceptTouchEvent(ev);
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev)
	{
		boolean callSuper = false;

		final int action = ev.getAction();
		switch (action)
		{
		case MotionEvent.ACTION_DOWN:
		{
			callSuper = true;
			mLastMotionX = ev.getX();
			mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
			break;
		}
		case MotionEventCompat.ACTION_POINTER_DOWN:
		{
			callSuper = true;
			final int index = MotionEventCompat.getActionIndex(ev);
			final float x = MotionEventCompat.getX(ev, index);
			mLastMotionX = x;
			mActivePointerId = MotionEventCompat.getPointerId(ev, index);
			break;
		}
		case MotionEvent.ACTION_MOVE:
		{
			if (mActivePointerId != INVALID_POINTER_ID)
			{
				// Scroll to follow the motion event
				final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
				final float x = MotionEventCompat.getX(ev, activePointerIndex);
				final float deltaX = mLastMotionX - x;
				final int width = getWidth();
				final int widthWithMargin = width + getPageMargin();
				final int lastItemIndex = getAdapter().getCount() - 1;
				final int currentItemIndex = getCurrentItem();
				final float leftBound = Math.max(0, (currentItemIndex - 1) * widthWithMargin);
				final float rightBound = Math.min(currentItemIndex + 1, lastItemIndex) * widthWithMargin;
				if (mScrollPositionOffset == 0)
				{
					if (currentItemIndex == 0)
					{
						if (leftBound == 0)
						{
							final float over = deltaX + mTouchSlop;
							mOverscrollEffect.setPull(over / width);
						}
					}
					else if (lastItemIndex == currentItemIndex)
					{
						if (rightBound == lastItemIndex * widthWithMargin)
						{
							final float over = deltaX - mTouchSlop;
							mOverscrollEffect.setPull(over / width);
						}
					}
				}
				else
				{
					mLastMotionX = x;
				}
			}
			else
			{
				mOverscrollEffect.onRelease();
			}
			break;
		}
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_CANCEL:
		{
			callSuper = true;
			mActivePointerId = INVALID_POINTER_ID;
			mOverscrollEffect.onRelease();
			break;
		}
		case MotionEvent.ACTION_POINTER_UP:
		{
			final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
			final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
			if (pointerId == mActivePointerId)
			{
				// This was our active pointer going up. Choose a new
				// active pointer and adjust accordingly.
				final int newPointerIndex = pointerIndex == 0 ?

1 : 0;
				mLastMotionX = ev.getX(newPointerIndex);
				mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
				callSuper = true;
			}
			break;
		}
		}

		if (mOverscrollEffect.isOverscrolling() && !callSuper)
		{
			return true;
		}
		else
		{
			try
			{
				return super.onTouchEvent(ev);
			}
			catch (IllegalArgumentException ignore)
			{
			}
			catch (ArrayIndexOutOfBoundsException ignore)
			{
			}
			return false;
		}
	}

	@Override
	protected boolean getChildStaticTransformation(View child, Transformation t)
	{
		if (child.getWidth() == 0)
		{
			return false;
		}

		final boolean isFirstOrLast = mScrollPosition == 0 || (mScrollPosition == (getAdapter().getCount() - 1));
		if (mOverscrollEffect.isOverscrolling() && isFirstOrLast)
		{
			final float dx = getWidth() / 2;
			final int dy = getHeight() / 2;
			t.getMatrix().reset();
			final float translateZ = (float) (mOverscrollTranslation * Math.sin(Math.PI
					* Math.abs(mOverscrollEffect.mOverscroll)));
			final float degrees = 90 / mOverscrollRotation
					- (float) ((RADIANS * Math.acos(mOverscrollEffect.mOverscroll)) / mOverscrollRotation);

			mCamera.save();
			mCamera.rotateY(degrees);
			mCamera.translate(0, 0, translateZ);
			mCamera.getMatrix(t.getMatrix());
			mCamera.restore();
			t.getMatrix().preTranslate(-dx, -dy);
			t.getMatrix().postTranslate(dx, dy);

			if (mAnimateAlpha)
			{
				t.setTransformationType(Transformation.TYPE_BOTH);
				t.setAlpha((FloatMath.sin((float) ((1 - Math.abs(mOverscrollEffect.mOverscroll)) * Math.PI / 2))));
			}
			return true;
		}
		else if (mScrollPositionOffset > 0)
		{

			final float dx = getWidth() / 2;
			final float dy = getHeight() / 2;

			double degrees = 0;
			child.getLocalVisibleRect(mTempTect);

			if (mTempTect.left >= mScrollPositionOffsetPixels)
			{
				if (mAnimateAlpha)
				{
					t.setTransformationType(Transformation.TYPE_BOTH);
					t.setAlpha((FloatMath.sin((float) (mScrollPositionOffset * Math.PI / 2))));
				}
				// right side
				degrees = (90 / mSwipeRotation) - (RADIANS * Math.acos(mScrollPositionOffset)) / mSwipeRotation;
			}
			else if (mTempTect.left == 0)
			{
				if (mAnimateAlpha)
				{
					t.setTransformationType(Transformation.TYPE_BOTH);
					t.setAlpha((FloatMath.sin((float) (mScrollPositionOffset * Math.PI / 2 + Math.PI / 2))));
				}
				// left side
				degrees = -(90 / mSwipeRotation) + (RADIANS * Math.acos(1 - mScrollPositionOffset)) / mSwipeRotation;
			}

			final float translateZ = (mSwipeTranslation * FloatMath.sin((float) ((Math.PI) * mScrollPositionOffset)));
			// Log.i(DEBUG_TAG, visibleRect.left+ ", " + mScrollPositionOffsetPixels + ", degress = "+
			// String.format("%f.2", degrees));

			t.getMatrix().reset();
			mCamera.save();
			mCamera.rotateY((float) degrees);
			mCamera.translate(0, 0, translateZ);
			mCamera.getMatrix(t.getMatrix());
			mCamera.restore();
			// pivot point is center of child
			t.getMatrix().preTranslate(-dx, -dy);
			t.getMatrix().postTranslate(dx, dy);
			// child.invalidate();
			return true;
		}
		return false;
	}
}

2.Activity中使用ViewPager3D

package com.example.pageradapterdemo;

import java.util.ArrayList;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

import com.focustech.common.widget.scrollviewpager.ViewPager3D;

public class MainActivity extends FragmentActivity
{

	private ViewPager3D mViewPager;
	private CommonFragmentAdapter mAdapter;
	private ArrayList<MyFragment> mList;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		initData();
		initView();
	}

	private void initView()
	{

		mViewPager = (ViewPager3D) findViewById(R.id.viewpager);
		mAdapter = new CommonFragmentAdapter(MainActivity.this, getSupportFragmentManager(), mList);
		mViewPager.setAdapter(mAdapter);
	}

	private void initData()
	{

		mList = new ArrayList<MyFragment>();

		MyFragment layout1 = new MyFragment("One Fragment");

		MyFragment layout2 = new MyFragment("Two Fragment");

		MyFragment layout3 = new MyFragment("Three Fragment");

		mList.add(layout1);
		mList.add(layout2);
		mList.add(layout3);

	}
}

3.CommonFragemntAdapter为ViewPager3D填充Fragment

public class CommonFragmentAdapter extends FragmentStatePagerAdapter
{
	private ArrayList<MyFragment> fragmentList;

	public CommonFragmentAdapter(Activity activity, FragmentManager fm, ArrayList<MyFragment> fragmentList)
	{
		super(fm);
		this.fragmentList = fragmentList;
	}

	@Override
	public Fragment getItem(int arg0)
	{
		return fragmentList.get(arg0);
	}

	@Override
	public int getCount()
	{
		return fragmentList.size();
	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object)
	{
		super.destroyItem(container, position, object);
	}
}

总结:将ViewPager3D当作一个普通的ViewPager来使用就可以。

时间: 2024-11-02 10:51:40

android自己定义ViewPager之——3D效果应用的相关文章

android自定义ViewPager之——3D效果应用

今天在github里看到一个3D效果的ViewPager,感觉做出来的ViewPager滑动的时候效果十分的炫,就check out下来研究了一下如何实现的,以及如何使用,将整个ViewPager稍加修改后(主要是处理了一下与项目中其它控滑动控件的事件冲突)后,应用到了自己现在项目中.感觉这个效果真的非常的不错,现在把自己写的一个Demo分享出来. 下面是这个ViewPager嵌入到项目中的效果图: 修改以后,在切换ViewPager时会有立体感,会为自己的应用增色不少.下面把使用的Demo发出

利用ViewPager实现3D画廊效果及其图片加载优化

前言 对于ViewPager,相信大家都已经很熟悉了,在各种切换场景比如Fragment切换.选项卡的切换或者顶部轮播图片等都可以用ViewPager去实现.那么本篇文章带来ViewPager的一种实现效果:3D画廊.直接上图来看: 从上面的图我们可以看出,整个页面分成三个部分,中间的是大图,正中地显示给用户:而两边的是侧图,而这两幅图片又有着角度的旋转,与大图看起来不在同一平面上,这就形成了3D效果.接着拖动页面,侧面的图慢慢移到中间,这个过程也是有着动画的,包括了图片的旋转.缩放和平移.在欣

Android ViewPager打造3D画廊

网上有很多关于使用Gallery来打造3D画廊的博客,但是在关于Gallery的官方说法中表明: This class was deprecated in API level 16.This widget is no longer supported. Other horizontally scrolling widgets include HorizontalScrollView and ViewPager from the support library.(来自:https://develo

android UI之ViewPager多页面滑动效果

  viewPager实现引导页 ViewPager多页面滑动效果 1.Android的左右滑动在实际编程经常能用到,比如查看多张图片,左右 切换tab页. 2.自android 3.0之后的SDK中提供了android-support-V4包用以实现 版本兼容,让老版本系统下的应用通过加入jar包实现扩展,其中有一 个可以实现左右滑动的类ViewPager 今天我们就用ViewPager类来实现引导页的实战案例 实现功能: 1.实现ViewPager多页面滑动效果. 2.下方的显示当前

Android -- 使用ViewPager实现画廊效果

1,今天在微信推送文章看到实现画廊效果,感觉挺不错的,就来写写试试,先来看一下效果图: 上面的效果基本上可以用两个功能点来包含:ViewPager的切换动画.ImageView的倒影的实现 嗯,先来将我们主要的功能来实现,就是我们的ViewPager展示图片 主界面的布局: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.

Android照片墙加强版,使用ViewPager实现画廊效果

转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/12646775 记得关于照片墙的文章我已经写过好几篇了,有最基本的照片墙,有瀑布流模式的照片墙,后来又在瀑布流的基础之上加入了查看大图和多点触控缩放的功能.总体来说,照片墙这个Demo在这几篇文章的改进中已经变得较为完善了,本想关于这个功能的系列到此为止,但有朋友跟我反应,觉得在查看大图的时候最好能通过左右滑动来浏览前后的图片.恩,确实,好像比较高端的一些应用都有这样的效果,那么本

Android开发之ViewPager实现轮播图(轮播广告)效果的自定义View

最近开发中需要做一个类似京东首页那样的广告轮播效果,于是采用ViewPager自己自定义了一个轮播图效果的View. 主要原理就是利用定时任务器定时切换ViewPager的页面. 效果图如下: 主页面布局实现如下: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android&

Android 自己定义控件实现刮刮卡效果 真的就仅仅是刮刮卡么

转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/40162163 , 本文出自:[张鸿洋的博客] 非常久以前也过一个html5的刮刮卡效果~~上次看到有人写Android的刮刮卡效果~~于是乎产生了本篇博客~~此类样例也比較多了,大家能够百度看看~只是还是通过本样例,带大家发掘一下.里面隐含的知识~ 1.Xfermode以及PorterDuff 假设大家还记得,以前在博客:完美实现图片圆角和圆形 简介过圆角的实现原理也是基于这个

Android UI-自定义日历控件

Android UI-自定义日历控件 本篇博客笔者给大家分享一个日历控件,这里有个需求:要求显示当前月的日期,左右可以切换月份来查看日期. 我们想一想会如何去实现这样的一个控件,有开源的,但可能不太满足我们的特定的需求,这里笔者自定义了一个,读者可以根据自己的需求来修改代码.下面来说一下实现的思路: 首先我们要显示当前月份,自然我们要计算出当前的日期,并且把每一天对应到具体的星期,我们会有以下效果: 我们先想一下这样的效果用什么控件可以实现?很自然可以想到用网格视图GridView,但这里笔者使