Simple use of Android Viewpager

Source: Internet
Author: User

Simple use of Android Viewpager

Android-support-v4.jar is a software package that Google offers to us for a compatible low-version Android device that contains only the APIs available on Android 3.0. And Viewpager is one of them. With it, we can do a lot of things, from the simplest navigation, to the page menu and so on.

Get ready

Before using Viewpager, you need to include the following statement in the Build.gradle:

compile ‘com.android.support:support-v4:25.3.0‘compile ‘com.github.hackware1993:MagicIndicator:1.5.0‘

The first line is the ANDROID-SUPPORT-V4 software package, Viewpager is on the inside; the second line is an open source navigator, through which we can achieve a variety of navigation effects.

Viewpager--Basic usage

The basic usage of Viewpager can be divided into the following steps:

    1. Define a Viewpager component in the layout file;
    2. Obtain Viewpager references in Activity (or fragment, etc.);
    3. Set the adapter for Viewpager;
    4. [Set slide effect for Viewpager];
    5. [Set listener for Viewpager].

The last two steps are optional, but without the last two steps, our viewpager is just an ordinary viewpager.
Let's write a simple example where you put some pictures in the Drawable folder beforehand, and the images page begin with:

<?xmlVersion= "1.0" encoding= "Utf-8"?><relativelayoutxmlns: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"tools:context="Com.zzw.activity.PageActivity">    <android.support.v4.view.viewpagerandroid:layout_width="Match_parent"android:layout_height="Match_parent"android:id="@+id/view_pager"android:background="@android: Color/black" /></RelativeLayout>

We define a Viewpager component in the layout file, and then we need to set it in the Activity:

Pager= (Viewpager)Findviewbyid(R.ID.View_pager); Pageradapter adapter=New Viewadapter(pages);p ager.Setadapter(adapter);classViewadapterextendsPageradapter {PrivateList<view> datas; Public Viewadapter(list<view> List)    {datas=list; }@Override     Public int GetCount() {returnDatas.size(); }@Override     Public Boolean Isviewfromobject(View view, Object object) {returnView==object; }@Override     PublicObjectInstantiateitem(ViewGroup container,intPosition) {View View=datas.Get(position); Container.AddView(view);returnView }@Override     Public void Destroyitem(ViewGroup container,intPosition, Object object) {container.Removeview(Datas.Get(position)); }}

Well, now we're done with a "picture browser" that works like this:

PS: You may notice that we have a navigator at the bottom because this is the effect of adding a navigator (it's too lazy to go back and change it again).
So you might ask, how does this navigator come into being, and why is it not in the code above? Don't worry, because this open source navigator is really too cow B, so I would like to use a section to introduce, if you can't wait, you can also see the navigator introduction.

Well, now we are basically familiar with the basic use of Viewpager, but! The effect of Viewpager is much more than that, and we look down.

Viewpager--the effect of the surface

Well, now we're going to add some special effects to the "picture browser" above (otherwise the user must be tired of the aesthetic). Imagine, when we slide the picture, if the next picture can be "surfaced" from behind, is not very good! Okay, so let's try adding this special effect.
But where do we start? Haha, in fact, Google has already provided us with the corresponding API, is Android.support.v4.view.ViewPager.PageTransformer this interface, any implementation of this interface class can be Viewpager Provides a special effect oh.
We found that there is only one method in this interface public void Transformpage (View page, float position), to see its two parameters, page representing a page in Viewpager, position representing page The current position, [-1, 0] indicates that the left side of the screen ( page partially visible), [0, 0] is on the screen page (fully visible), (0, 1] for the right side of the screen page (partially visible), see:

When page sliding to the left, position change from 0 to 1, when it is completely invisible, and when you position==-1 page swipe right, position change from 0 to 1, when position==1 it is completely invisible.
If you want more in-depth understanding position of the law (perhaps I did not express clearly), you can refer to the article "Android to achieve the personality of the Viewpager switch Animation combat Pagetransformer (compatible with Android3.0 below)".
Well, after the instructions above, we found that only the range of [-1, 1] would be processed position :

 Public classScalepagetransformerImplementsViewpager.Pagetransformer{Private Static Final floatmin_scale=0.75f;@Override     Public void Transformpage(View page,floatPosition) {//log.d ("TAG", "<" +page.hashcode () + "," +position+ ">");        // out of left screen        if(position<-1.0f) {page.Setscalex(Min_scale); Page.Setscaley(Min_scale); }//Slide left        Else if(position<=0.0f) {page.Setalpha(1.0f); Page.Settranslationx(0.0f); Page.Setscalex(1.0f); Page.Setscaley(1.0f); }//Slide right        Else if(position<=1.0f) {page.Setalpha(1.0f-position); Page.Settranslationx(-page.getwidth() *position);floatScale=min_scale+ (1.0f-min_scale) * (1.0f-position); Page.Setscalex(scale); Page.Setscaley(scale); }// out of right screen        Else{page.Setscalex(Min_scale); Page.Setscaley(Min_scale); }    }}

Then add this special effect to the Viewpager:

pager.setPageTransformer(truenewScalePageTransformer());

Now the effect is as follows:

Haha, our "picture browser" is not good looking a big cut. But, don't rush away, we can also achieve more special effects.

Viewpager--Rotary effects

With the foundation above, let's do a spin effect here:

 Public classRotatepagetransformerImplementsViewpager.Pagetransformer{Private Static Final floatmax_rotation=.0f;@Override     Public void Transformpage(View page,floatPosition) {if(position<-1)Rotate(page,-max_rotation);Else if(position<=1)Rotate(page, max_rotation*position);Else            Rotate(page, max_rotation); }Private void Rotate(View view,floatRotation) {view.Setpivotx(View.getwidth()*0.5f); View.Setpivoty(View.getheight()); View.setrotation(rotation); }}

This is more simple, just depend on position the angle of rotation. The effect is as follows:

Viewpager--3D Gallery

Here we will achieve a special effect, but this effect is slightly more complex, but the effect is really cool! Let's look at the effect first:

It's like being in a 3D gallery. Well, here's what we're going to do to achieve this effect.
First or Pagetransformer:

 Public classGallerypagetransformerImplementsViewpager.Pagetransformer{Private Static Final floatmax_rotation=.0f;Private Static Final floatmin_scale=0.75f;Private Static Final floatMax_translate=.0f;@Override     Public void Transformpage(View page,floatPosition) {if(position<-1) {page.Settranslationx(max_translate); Page.Setscalex(Min_scale); Page.Setscaley(Min_scale); Page.Setrotationy(-max_rotation); }Else if(position<=0) {page.Settranslationx(-max_translate*position);floatScale=min_scale+ (1-min_scale) * (1.0f+position); Page.Setscalex(scale); Page.Setscaley(scale); Page.Setrotationy(max_rotation*position); }Else if(position<=1) {page.Settranslationx(-max_translate*position);floatScale=min_scale+ (1-min_scale) * (1.0f-position); Page.Setscalex(scale); Page.Setscaley(scale); Page.Setrotationy(max_rotation*position); }Else{page.Settranslationx(-max_translate); Page.Setscalex(Min_scale); Page.Setscaley(Min_scale); Page.Setrotationy(max_rotation); }    }}

Here the "3D" effect is mainly achieved by the view.setrotationy (float rotation) method, the role of this method is to let the view around the Y axis to rotate a certain angle (about Android's three-dimensional coordinate system please do their own query).
See this, you may ask, where is the reflection? Don't worry, we don't realize the reflection in the Pagetransformer, but we have it from the beginning. Yes, when we set up the adapter for Viewpager, we encapsulate the image of the reflection directly into the adapter.
The following method is responsible for generating images with reflections:

 Public StaticBitmapGetreversebitmapbyid(Context context,intResId,floatpercent) {//Get the source bitmapBitmap srcbitmap=bitmapfactory.Decoderesource(Context.getresources(), resId);//Get the tow third segment of the reverse bitmapMatrix matrix=New Matrix(); Matrix.Setscale(1, -1); Bitmap Rvsbitmap=bitmap.CreateBitmap(Srcbitmap,0, (int) (Srcbitmap.getheight()*(1-percent)), Srcbitmap.getwidth(), (int) (Srcbitmap.getheight() *percent), Matrix,false);//combine the source bitmap and the reverse bitmapBitmap Combitmap=bitmap.CreateBitmap(Srcbitmap.getwidth(), Srcbitmap.getheight() +rvsbitmap.getheight()+ -, Srcbitmap.GetConfig()); Canvas gcanvas=NewCanvas (COMBITMAP); Gcanvas.Drawbitmap(Srcbitmap,0,0,NULL); Gcanvas.Drawbitmap(Rvsbitmap,0, Srcbitmap.getheight()+ -,NULL); Paint paint=NewPaint (); LinearGradient shader=New lineargradient(0, Srcbitmap.getheight()+ -,0, Combitmap.getheight(), Color.BLACK, Color.TRANSPARENT, Shader.Tilemode.CLAMP); Paint.Setshader(shader); Paint.Setxfermode(New Porterduffxfermode(Porterduff.Mode.dst_in)); Gcanvas.DrawRect(0, Srcbitmap.getheight()+ -, Srcbitmap.getwidth(), Combitmap.getheight(), paint);returnCombitmap;}

The percent parameter specifies the ratio of the reflection to the original image.
The original image is then processed:

PrivateList<view>getpages() {list<view> pages=NewArraylist<> (); Field[] Fields=r.drawable.class.Getdeclaredfields();Try{ for(Field field:fields) {if(field.GetName().StartsWith("Page") {ImageView view =NewImageView ( This); View.Setimagebitmap(Imageutils.Getreversebitmapbyid( This, field.getInt(NULL),0.5f)); Pages.Add(view); }        }    }Catch(Illegalaccessexception e) {e.Printstacktrace(); }returnpages;}

Now we have a beautiful "3D Gallery":

Magicindicator--magic!!!

So far, the introduction to Viewpager is over. But, have you found that when we slide the picture, do not know the current is the first few pictures (our picture is very few, if more words will have this problem)!!!
To solve this problem, we also need an indicator/navigator to specify the current position. However, the thought of having to implement an indicator from scratch is a big head (a simple indicator, of course, is easy). Fortunately, there are magicindicator to help you.
Magicindicator, "People" as its name, it is characterized by "MAGIC"!!! Not much to say, first look at it:

See this effect I kneel directly! A detailed introduction to Magicindicator can be seen in these articles:

    1. One of the series-use Magicindicator to create the ever-changing Viewpager indicator
    2. Series II--magicindicator Guide to the use of
    3. Analysis of three--magicindicator principles of Magicindicator Series and 4 ways of extending Magicindicator

*magicindicator's github address is: Https://github.com/hackware1993/MagicIndicator, about its specific usage is also on top, here we don't say much. *

Viewpager and Fragment

The

Viewpager is often combined with Fragment to implement various page transitions, such as the page menu that we mentioned at the beginning. Since the use of Fragment in Viewpager is slightly different from the way described above, let's take a look at this separately. Think about it, our previous Viewpager page is View, and now we want to replace it with Fragment, do you need a replacement adapter? Yes, that's true, but there's no need to write an adapter from scratch, and Google offers us two abstract classes: Fragmentpageradapter and Fragmentstatepageradapter. Whether inheriting fragmentpageradapter or fragmentstatepageradapter, you need to implement constructors, int GetCount (), and Fragment getItem (int position) methods. Here's our example:

public   Fragmentadapter extends  fragmentpageradapter {private     List<fragment> datas; public  fragmentadapter  (Fragmentmanager FM, list<fragment> List)        {super  (FM);    Datas=list; }  @Override  public  int   () {return  datas. (); }  @Override  public  Fragment getitem  (int  position) {return  datas. (position); }}

Each of the Fragment in the fragmentpageradapter is stored in memory, so it is suitable for relatively static, low-volume situations, if there are many pages to deal with, and the data is more dynamic and memory-intensive. You should use Fragmentstatepageradapter. Fragmentstatepageradapter, like Fragmentpageradapter, inherits from Pageradapter. But unlike Fragmentpageradapter, it retains only the current page, just as the "state" in its class name implies. When the page is out of sight, it is recycled, releasing its resources, and when the page needs to be displayed, a new page is generated. The advantage is that when you have a large number of pages, you do not consume large amounts of memory in memory. After you have an adapter for Fragment, you also need to set the adapter for Viewpager:

FragmentAdapter adapter=newFragmentAdapter(getSupportFragmentManager(), frags);pager.setAdapter(adapter);

The final results are as follows:

Simple use of Android Viewpager

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.