Monday, 21 July 2014

HB Blog 4: View pager animation using page transformation for Android.

Viewpager:-

 Layout manager that allows the user to flip left and right through pages of data. You supply an implementation of a PagerAdapter to generate the pages that the view shows.
ViewPager is most often used in conjunction with Fragment, which is a convenient way to supply and manage the lifecycle of each page. There are standard adapters implemented for using fragments with the ViewPager, which cover the most common use cases. These are FragmentPagerAdapter and FragmentStatePagerAdapter; each of these classes have simple code showing how to build a full user interface with them.

For more information regarding view pager follow below link:-
 http://developer.android.com/reference/android/support/v4/view/ViewPager.html

View pager animation for pages transition using page transformation:-

It is pretty simple,

1)Create viewpager and its pager adapter.Follow below code snippet  or refer above viewpager link.


1
2
3
4
5
//view pager instance...
final ViewPager viewPager = (ViewPager)findViewById(R.id.myViewPager);
viewPager.setAdapter(pageAdapter);
//your page adapter instance...
MyPagerAdapter pageAdapter = new MyPagerAdapter(getSupportFragmentManager()
2)Now, just attach a PageTransformer to the ViewPage.


1
2
3
4
5
6
7
viewPager.setPageTransformer(false, new PageTransformer() {
            @Override
            public void transformPage(View page, float position) {
                        // do transformation here
            }
        });
    } 
3)Find out few below examples.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
//For Alpha Transformation:-

 viewPager.setPageTransformer(false, new PageTransformer() {
 @Override
            public void transformPage(View page, float position) {
                /**ALPHA TRANSFORMATION**/
                final float normalizedposition = Math.abs(Math.abs(position) - 1);
                page.setAlpha(normalizedposition);
            }
        });

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
//For Scaling Transformation:-

 viewPager.setPageTransformer(false, new PageTransformer() {
            @Override
            public void transformPage(View page, float position) {
                /**SCALING TRANSFORMATION**/
                final float normalizedposition = Math.abs(Math.abs(position) - 1);
                page.setScaleX(normalizedposition / 2 + 0.5f);
                page.setScaleY(normalizedposition / 2 + 0.5f);
            }
        });


1
2
3
4
5
6
7
8
9
//For Rotation Transformation:-

viewPager.setPageTransformer(false, new PageTransformer() {
            @Override
            public void transformPage(View page, float position) {
                /**ROATAION TRANSFORMATION**/
                page.setRotationY(position * -30);
            }
        });


4)Happy coding :)

Refer the below link for complete sample code:-
Download Sample Code
Download Apk File 

3 comments: