您好,登錄后才能下訂單哦!
1、概述
之前寫過一篇博文:Android 自定義 ViewPager 打造千變?nèi)f化的圖片切換效果。有兄弟提出,ViewPager自帶了一個setPageTransformer用于設(shè)置切換動畫~
本篇博文,將:
1、介紹如何使用setPageTransformer設(shè)置切換動畫;
2、自定義PageTransformer實現(xiàn)個性的切換動畫;
3、該方法在SDK11以下的版本不起作用,我們會對其做一定修改,讓其向下兼容。
官方示例地址:http://developer.android.com/training/animation/screen-slide.html 有興趣的可以去看看~~
好了,下面開始編寫代碼~~
2、setPageTransformer的使用
首先我們迅速的實現(xiàn)一個傳統(tǒng)的ViewPager效果~
1、布局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <android.support.v4.view.ViewPager android:id="@+id/id_viewpager" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </RelativeLayout>
2、MainActivity
package com.zhy.demo_zhy_08_viewpageranim; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.ImageView; import android.widget.ImageView.ScaleType; public class MainActivity extends Activity { private ViewPager mViewPager; private int[] mImgIds = new int[] { R.drawable.guide_image1, R.drawable.guide_image2, R.drawable.guide_image3 }; private List<ImageView> mImageViews = new ArrayList<ImageView>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); initData(); mViewPager = (ViewPager) findViewById(R.id.id_viewpager); mViewPager.setAdapter(new PagerAdapter() { @Override public Object instantiateItem(ViewGroup container, int position) { container.addView(mImageViews.get(position)); return mImageViews.get(position); } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView(mImageViews.get(position)); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public int getCount() { return mImgIds.length; } }); } private void initData() { for (int imgId : mImgIds) { ImageView imageView = new ImageView(getApplicationContext()); imageView.setScaleType(ScaleType.CENTER_CROP); imageView.setImageResource(imgId); mImageViews.add(imageView); } } }
好了,這樣一個傳統(tǒng)ViewPager就實現(xiàn)了~~大家對上面代碼應(yīng)該不會有任何陌生的感覺~運行效果也不用貼圖了,大家肯定知道~~
3、PageTransformer
ViewPager有個方法叫做:
setPageTransformer(boolean reverseDrawingOrder, PageTransformer transformer) 用于設(shè)置ViewPager切換時的動畫效果,并且google官方還給出了兩個示例。
只需要在上述代碼中調(diào)用setPageTransformer即可添加切換動畫效果~~下面演示google的兩個PageTransformer的代碼,以及運行效果。
1、DepthPageTransformer
public class DepthPageTransformer implements ViewPager.PageTransformer { private static final float MIN_SCALE = 0.75f; public void transformPage(View view, float position) { int pageWidth = view.getWidth(); 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.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); } } }
調(diào)用代碼:
mViewPager.setPageTransformer(true, new DepthPageTransformer());
效果:
2、ZoomOutPageTransformer
package com.zhy.view; import android.annotation.SuppressLint; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.View; public class ZoomOutPageTransformer implements ViewPager.PageTransformer { private static final float MIN_SCALE = 0.85f; private static final float MIN_ALPHA = 0.5f; @SuppressLint("NewApi") public void transformPage(View view, float position) { int pageWidth = view.getWidth(); int pageHeight = view.getHeight(); Log.e("TAG", view + " , " + position + ""); if (position < -1) { // [-Infinity,-1) // This page is way off-screen to the left. view.setAlpha(0); } else if (position <= 1) //a頁滑動至b頁 ; a頁從 0.0 -1 ;b頁從1 ~ 0.0 { // [-1,1] // Modify the default slide transition to shrink the page as well 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); } // Scale the page down (between MIN_SCALE and 1) view.setScaleX(scaleFactor); view.setScaleY(scaleFactor); // Fade the page relative to its size. view.setAlpha(MIN_ALPHA + (scaleFactor - MIN_SCALE) / (1 - MIN_SCALE) * (1 - MIN_ALPHA)); } else { // (1,+Infinity] // This page is way off-screen to the right. view.setAlpha(0); } } }
調(diào)用代碼:
mViewPager.setPageTransformer(true, new ZoomOutPageTransformer());
效果:
效果圖都是google官網(wǎng)上的,我們的測試圖會在兼容3.0以下貼出來,不然就重復(fù)了~~
為ViewPager添加切換就一行代碼是不是很happy,可惜是不兼容3.0以下的版本的,該方法的注釋上寫到:
setting a PageTransformer prior to Android 3.0 (API 11) will have no effect 在3.0之前的版本設(shè)置此方法是沒有效果的,那么下面我們就看如何讓其兼容3.0以下版本。
3、版本的向下兼容
1、不兼容的原因
首先看下為什么不兼容,3.0以下呢?
看上面的兩個示例代碼,代碼中View的動畫使用的是屬性動畫,而屬性動畫是3.0才推出的,那么這么寫肯定是不兼容3.0以下了~
那么我們首先引入nineoldandroids,讓動畫先能在3.0以下跑再說:
修改DepthPageTransformer
package com.zhy.view; import com.nineoldandroids.view.ViewHelper; import android.annotation.SuppressLint; import android.support.v4.view.ViewPager; import android.view.View; public class DepthPageTransformer implements ViewPager.PageTransformer { private static final float MIN_SCALE = 0.75f; public void transformPage(View view, float position) { int pageWidth = view.getWidth(); if (position < -1) { // [-Infinity,-1) // This page is way off-screen to the left. // view.setAlpha(0); ViewHelper.setAlpha(view, 0); } else if (position <= 0)// a頁滑動至b頁 ; a頁從 0.0 -1 ;b頁從1 ~ 0.0 { // [-1,0] // Use the default slide transition when moving to the left page // view.setAlpha(1); ViewHelper.setAlpha(view, 1); // view.setTranslationX(0); ViewHelper.setTranslationX(view, 0); // view.setScaleX(1); ViewHelper.setScaleX(view, 1); // view.setScaleY(1); ViewHelper.setScaleY(view, 1); } else if (position <= 1) { // (0,1] // Fade the page out. // view.setAlpha(1 - position); ViewHelper.setAlpha(view, 1 - position); // Counteract the default slide transition // view.setTranslationX(pageWidth * -position); ViewHelper.setTranslationX(view, pageWidth * -position); // Scale the page down (between MIN_SCALE and 1) float scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (1 - position); // view.setScaleX(scaleFactor); ViewHelper.setScaleX(view, scaleFactor); // view.setScaleY(1); ViewHelper.setScaleY(view, scaleFactor); } else { // (1,+Infinity] // This page is way off-screen to the right. // view.setAlpha(0); ViewHelper.setAlpha(view, 1); } } }
很簡單,把所有屬性動畫換成ViewHelper去設(shè)置就好了?,F(xiàn)在我們?nèi)?.0以下的機子上去運行,發(fā)現(xiàn)還是沒有效果~~~
為什么呢?
我們再去看看setPageTransformer的源碼:
public void setPageTransformer(boolean reverseDrawingOrder, PageTransformer transformer) { if (Build.VERSION.SDK_INT >= 11) { final boolean hasTransformer = transformer != null; final boolean needsPopulate = hasTransformer != (mPageTransformer != null); mPageTransformer = transformer; setChildrenDrawingOrderEnabledCompat(hasTransformer); if (hasTransformer) { mDrawingOrder = reverseDrawingOrder ? DRAW_ORDER_REVERSE : DRAW_ORDER_FORWARD; } else { mDrawingOrder = DRAW_ORDER_DEFAULT; } if (needsPopulate) populate(); } }
終于發(fā)現(xiàn)原因了,原來在此方法內(nèi)部判斷了如果是11以上的版本才讓動畫生效~~
那么,沒辦法了,如果想兼容,必須修改ViewPager的源碼了~~
2、完美向下兼容
我們將ViewPager的源碼拷貝一份至我們的項目中,修改名稱為ViewPagerCompat;然后注釋掉SDK版本判斷那一句
public class ViewPagerCompat extends ViewGroup {
public void setPageTransformer(boolean reverseDrawingOrder, ViewPager.PageTransformer transformer) { // if (Build.VERSION.SDK_INT >= 11) { final boolean hasTransformer = transformer != null; final boolean needsPopulate = hasTransformer != (mPageTransformer != null); mPageTransformer = transformer; setChildrenDrawingOrderEnabledCompat(hasTransformer); if (hasTransformer) { mDrawingOrder = reverseDrawingOrder ? DRAW_ORDER_REVERSE : DRAW_ORDER_FORWARD; } else { mDrawingOrder = DRAW_ORDER_DEFAULT; } if (needsPopulate) populate(); } }
...
}
注意,所有的PageTransformer使用ViewPager.PageTransformer
然后我們把項目中的ViewPager改為ViewPagerCompat;記得修改布局文件,以及MainActivity中的ViewPager為ViewPagerCompat
我們在2.3.3的模擬器上測試下效果:
可以看到,我們的切換動畫完美的運行在2.3.3的機器上~~so happy ~~沒有ViewPager源碼的童鞋不要緊,我會在文末的源碼下載中加入ViewPager源碼,讓你可以盡情去測試~~
當然了,僅僅是兼容當然不能滿足我們的好奇心,難道我們做到了兼容,還只能使用Google給的示例動畫么~~我們強大的創(chuàng)新呢~~下面帶領(lǐng)大家分析setPageTransformer方法,然后設(shè)計一個個性的動畫切換效果
4、自定義PageTransformer實現(xiàn)個性切換動畫
public interface PageTransformer { /** * Apply a property transformation to the given page. * * @param page Apply the transformation to this page * @param position Position of page relative to the current front-and-center * position of the pager. 0 is front and center. 1 is one full * page position to the right, and -1 is one page position to the left. */ public void transformPage(View page, float position); }
可以看到該接口只有一個方法,第一個是我們的view,第二個是position~~
當我們滑動時:會打印出當然ViewPager中存活的每個View以及它們的position的變化~~注意是每一個,所以建議別只log position,不然你會覺得莫名其妙的輸出~~
position的可能性的值有,其實從官方示例的注釋就能看出:
[-Infinity,-1) 已經(jīng)看不到了
(1,+Infinity] 已經(jīng)看不到了
[-1,1]
重點看[-1,1]這個區(qū)間 , 其他兩個的View都已經(jīng)看不到了~~
假設(shè)現(xiàn)在ViewPager在A頁現(xiàn)在滑出B頁,則:
A頁的position變化就是( 0, -1]
B頁的position變化就是[ 1 , 0 ]
知道了我們滑動時position的變化~~那么就開始設(shè)計我們的個性的切換效果;
官方給的例子,有變化透明度、偏移量、縮放的,我們準備來個不一樣的,我們變化角度,即rotation;
大概的效果是這樣的:
下面我們分析代碼:
我們設(shè)置View的旋轉(zhuǎn)中心為:
ViewHelper.setPivotX(view, view.getMeasuredWidth() * 0.5f);
ViewHelper.setPivotY(view, view.getMeasuredHeight());
依然是ViewPager在A頁現(xiàn)在滑出B頁
那么A頁應(yīng)當在滑動過程中0度到-20度的偏移,B頁應(yīng)當在滑動過程中+20度到0度的偏移
結(jié)合
A頁的position變化就是( 0, -1]
B頁的position變化就是[ 1 , 0 ]
那么旋轉(zhuǎn)的角度即:mRot = (20 * position); A頁 mRot :0 ,~ -20 ; B頁 mRot :20 ~ 0 ;
瞬間覺得好簡單:
完整代碼:
public interface PageTransformer { /** * Apply a property transformation to the given page. * * @param page Apply the transformation to this page * @param position Position of page relative to the current front-and-center * position of the pager. 0 is front and center. 1 is one full * page position to the right, and -1 is one page position to the left. */ public void transformPage(View page, float position); }
你沒看錯,if else 里面代碼是一樣的,為了好理解特意沒有合并到一起~~~
到此,我們從setPageTransformer使用,到修改ViewPager做到向下兼容,直至自己定義出個性的切換效果 都已經(jīng)介紹完畢~~
大家可以發(fā)揮自己的創(chuàng)造力,做出各種神奇的動畫效果,ok,就到這里!
源碼點擊下載
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。