An introduction to the Viewpager View sliding switch class in Android _android

Source: Internet
Author: User
Tags object object stub

Viewpager Introduction Example
First let everyone have a global understanding, directly on the project, to see just through these lines of code, unexpectedly can complete such a powerful function.
Effect Chart:
The three-view sliding between the two is achieved.
The first view slides to the second view, and the second view to the third view.

First, new project, introduce Viewpager control
Viewpager. It is a class of add-on packages in the Google SDK that can be used to switch between screens.

1. Join in the main layout file

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" 
  xmlns:tools= "http:// Schemas.android.com/tools " 
  android:layout_width=" fill_parent " 
  android:layout_height=" Fill_parent 
  " tools:context= "Com.example.testviewpage_1.MainActivity" > 
 
<android.support.v4.view.viewpager 
  Android:id= "@+id/viewpager" 
  android:layout_width= "wrap_content" 
  android:layout_height= "Wrap_content" 
  android:layout_gravity= "center"/> 
 
</RelativeLayout> 

Where <android.support.v4.view.viewpager/> is the corresponding component of the Viewpager, where you want to slide it.

2, new three layout, for sliding switch view
from the effect diagram can also see that our three views are very simple, there is no control, you can certainly add a variety of controls, but here is a demo, only the principle can be, so I only use the background to distinguish the layout without layout.

The layout code is as follows:

Layout1.xml

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= 
"http://schemas.android.com/apk/" Res/android " 
  android:layout_width=" match_parent " 
  android:layout_height=" Match_parent " 
  android: Background= "#ffffff" 
  android:orientation= "vertical" > 
   
 
</LinearLayout> 

Layout2.xml

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= 
"http://schemas.android.com/apk/" Res/android " 
  android:layout_width=" match_parent " 
  android:layout_height=" Match_parent " 
  android: Background= "#ffff00" 
  android:orientation= "vertical" > 
   
 
</LinearLayout> 

Layout3.xml

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= 
"http://schemas.android.com/apk/" Res/android " 
  android:layout_width=" match_parent " 
  android:layout_height=" Match_parent " 
  android: Background= "#ff00ff" 
  android:orientation= "vertical" > 
   
 
</linearlayout><span style= "color:#" 660000; " > 
</span> 

Second, the Code combat
first on the overall code, and then step-by-step explanation.

Package com.example.testviewpage_1; 
Import java.util.ArrayList; 
Import java.util.List; 
 
Import Java.util.zip.Inflater; 
Import android.app.Activity; 
Import Android.os.Bundle; 
Import Android.support.v4.view.PagerAdapter; 
Import Android.support.v4.view.ViewPager; 
Import Android.view.LayoutInflater; 
Import Android.view.View; 
 
 
Import Android.view.ViewGroup; 
  public class Mainactivity extends activity {private View view1, View2, VIEW3; Private Viewpager Viewpager; Corresponding Viewpager private list<view> viewlist;//view array @Override protected void onCreate (Bundle sa 
    Vedinstancestate) {super.oncreate (savedinstancestate); 
     
    Setcontentview (R.layout.activity_main); 
    Viewpager = (Viewpager) Findviewbyid (R.id.viewpager); 
    Layoutinflater Inflater=getlayoutinflater (); 
    View1 = inflater.inflate (R.LAYOUT.LAYOUT1, NULL); 
    View2 = Inflater.inflate (r.layout.layout2,null); 
     VIEW3 = inflater.inflate (R.LAYOUT.LAYOUT3, NULL);
    Viewlist = new arraylist<view> ()//The View to be displayed is loaded into the array viewlist.add (VIEW1); 
    Viewlist.add (VIEW2); 
     
     
    Viewlist.add (VIEW3); Pageradapter pageradapter = new Pageradapter () {@Override public boolean isviewfromobject View arg0 
      , Object arg1) {//TODO auto-generated method stub return arg0 = = Arg1; @Override public int GetCount () {//TODO auto-generated method stub return View 
      List.size (); 
        @Override public void Destroyitem (ViewGroup container, int position, object object) { 
      TODO auto-generated Method Stub Container.removeview (Viewlist.get (position)); @Override public Object Instantiateitem (viewgroup container, int position) {//TODO Auto 
         
         
        -generated method Stub Container.addview (Viewlist.get (position)); Return Viewlist.get (PositiON); 
     
     
    } 
    }; 
     
  Viewpager.setadapter (Pageradapter); 
 } 
 
 
}

The amount of code is small, all in the OnCreate () function.
1, first look at the declaration of the meaning of the variable:

Private View View1, View2, view3; 
Private list<view> Viewlist;//view Array 
private Viewpager viewpager;//corresponding Viewpager 

First viewpager the corresponding <android.support.v4.view.ViewPager/> control.

View1,view2, view3 corresponds to our three layout, that Layout1.xml,layout2.xml,layout3.xml
Viewlist is an array of view, with the top three view

2, the following is their initialization process:

Viewpager = (Viewpager) Findviewbyid (R.id.viewpager); 
Layoutinflater Inflater=getlayoutinflater (); 
View1 = inflater.inflate (R.LAYOUT.LAYOUT1, null); 
View2 = Inflater.inflate (r.layout.layout2,null); 
VIEW3 = inflater.inflate (R.LAYOUT.LAYOUT3, null); 
 
Viewlist = new arraylist<view> ()//The View to be displayed is loaded into the array 
viewlist.add (view1); 
Viewlist.add (VIEW2); 
Viewlist.add (VIEW3); 

The initialization process is not very difficult, is to link the resources and variables layout, and finally add the instantiated view1,view2,view3 to the Viewlist
3, Pageadapter--pageview adapter
adapter This dongdong must not be Mossen, in the ListView also have adapters, ListView by rewriting the GetView () function to get the item currently to be loaded. And PageAdapter is not quite the same, after all, PageAdapter is a single view of the collection.

PageAdapter four functions that must be rewritten:

(1) Boolean isviewfromobject (View arg0, Object arg1)
(2) int GetCount ()
(3) void Destroyitem (ViewGroup container, int position,object Object)
(4) Object Instantiateitem (ViewGroup container, int position)
Let's take a look at each function and what we've done here:

@Override public 
int GetCount () { 
  //TODO auto-generated a stub return 
  viewlist.size (); 
} 

GetCount (): Returns the number of view to slide

@Override public 
void Destroyitem (ViewGroup container, int position, 
    object object) { 
  //TODO auto-generated method Stub 
  Container.removeview (Viewlist.get (position)); 
} 

Destroyitem (): Deletes the view of the specified location (position) from the current container;

@Override public 
Object instantiateitem (viewgroup container, int position) { 
  //TODO auto-generated method stub< C3/>container.addview (Viewlist.get (position)); 
     
     
    return Viewlist.get (position); 
  } 
; 

Instantiateitem (): Two things done, first: Add the current view to the container, second: return to the View

@Override Public 
Boolean isviewfromobject (View arg0, Object arg1) { 
  //TODO auto-generated method stub 
  return arg0 = = Arg1; 


Isviewfromobject (): For this function is not to explain first, we now know it to rewrite the line, we will rewrite it later.
The following will carefully explain the meaning of these functions, and the knowledge about key.

Four functions of Viewpager
I. Official notes
Pageradapter is more common than Adapterview. Viewpager uses a callback function to represent an updated step instead of using a view-recycling mechanism. Pageradapter can also implement view recycling or use a smarter way to manage views when needed, such as fragment that can manage its own view.

Viewpager does not directly process each view, but it links individual views to one key. This key is used to track and uniquely represent a page, and it is also independent of the adapter position of the page. When Pageradapter is about to change, he calls the Startupdate function, and then calls one or more times Instantiateitem or Destroyitem. Finally, the finishupdate is invoked later in the update. When Finishupdate returns, the object returned by Instantiateitem should be added to the parent ViewGroup Destroyitem The object returned should be viewgroup deleted. Methodisviewfromobject (View, Object) represents whether the current page is associated with a given key.
 
For very simple pageradapter perhaps you can choose to use the page itself as the key, after creating and adding to the ViewGroup Instantiateitem method to return the page itself
Destroyitem will remove the page from the ViewGroup. The Isviewfromobject method can return view = = Object directly.
&NBSP
Pageradapter supports changes to the data set, and changes to the data set must be performed inside the main thread, and then the Notifydatasetchanged method is called. Very similar to the baseadapter. Changes to the data set include deletion and modification of the page. Viewpager to maintain the current page is active, so you must provide a getitemposition method.

Second, analysis
instead of dealing directly with each view, Viewpager links each view to a key. This key is used to track and uniquely represent a page, and it is also independent of the adapter position of the page. When Pageradapter is about to change, he calls the Startupdate function, and then calls one or more times Instantiateitem or Destroyitem. Finally, the finishupdate is invoked later in the update. When Finishupdate returns, the object returned by Instantiateitem should be added to the parent ViewGroup Destroyitem The object returned should be viewgroup deleted. Methodisviewfromobject (View, Object) represents whether the current page is associated with a given key.

For very simple pageradapter maybe you can choose to use the page itself as the key, Returns the page itself after it is created and added to the ViewGroup Instantiateitem method Destroyitem will remove the page from the ViewGroup. The Isviewfromobject method can return view = = Object directly.

For the above two paragraphs, I have here two points to focus on:

1, the first paragraph explains the concept of key (keys), the first thing to be clear here is that each sliding page corresponds to a key, and this key value is used to track the unique page, that is, each sliding page with a unique key one by one corresponding. We first have this concept is good, about this key is how to come, the following to say.

2, the second paragraph of a simple talk about an application, the current page itself view as key. In fact, this application is the example used in our previous chapter. You don't understand? It's okay, let's talk about it. Now let's talk about the key problem.

Third, about key
now I'm going to take a look at the official documents of several methods:

1. First, Destroyitem ():

The function of this method is to remove a page from a given location. The adapter is responsible for removing this view from the container. This is to ensure that the view can be removed when finishupdate (ViewGroup) returns.
We do this in the example of the introduction section:

@Override public 
void Destroyitem (ViewGroup container, int position, 
    object object) { 
  //TODO auto-generated method Stub 
  Container.removeview (Viewlist.get (position)); 
} 

Sure enough, we removed the view of the given position from the container ...

2. Then look at GetCount ():

public abstract int GetCount ()

Return the number of views available.

Returns the number of active views currently in effect. Then we also:

@Override public 
int GetCount () { 
  //TODO auto-generated a stub return 
  viewlist.size (); 
} 

Returns the number of currently sliding views, consistent with official instructions.

Four, the hardest two are here.

1.instantiateItem (ViewGroup container, int position)
The function's implementation is to create a page view of the specified location. The adapter is obligated to add the view view that is about to be created to the container given here, in order to ensure that the this was is done! when Finishupdate (ViewGroup) returns
Return value: Returns an object (Key) that represents the new view page, where it is not necessary to return to the view itself or to other containers on this page. In fact, my understanding is to represent the current page of any value, as long as you can add to your view one by one can be, such as position variable can also be as key (finally we give an example to try it can not do)

Experience:

(1) From the description you can see that in the code, our responsibility is to add the view of the specified position to the Conatiner

(2) Key question: From this function we can see that the function return value is the corresponding to the view that we add to the Conatiner according to the parameter position key!!!!!!!

(3) "It only must ensure it returns Fromfinishupdate (ViewGroup)." This statement also appears in the function description of Destroyitem (), which shows that after Finishupdate (ViewGroup) is executed, there are two actions, one is the removal of the original view (the view that is no longer displayed), and the other is the new display view (the view that is about to be displayed).

Or as an example of the first introduction, we do this:

@Override public 
Object instantiateitem (viewgroup container, int position) { 
  //TODO auto-generated method stub< C3/>container.addview (Viewlist.get (position)); 
     
     
    return Viewlist.get (position); 
  } 
; 

Here we do two things
First: Add the view of the position given in the argument to the Conatiner for its creation and display.

Second: Return the current position view to do the key for this views. Remember the following passage from the official API documentation?
For very simple pageradapter maybe you can choose to use the page itself as the key, Returns the page itself after it is created and added to the ViewGroup Instantiateitem method Destroyitem will remove the page from the ViewGroup. The Isviewfromobject method can return view = = Object directly.

This is where the current view is passed out as a key!!!!

2.isViewFromObject (View view, Object object)
function: This function is used to determine whether the key returned by the Instantiateitem (viewgroup, int) function is the same view represented by a page view (that is, whether it corresponds to the corresponding representation of a view)
Return value: Returns True if the corresponding is the same view, otherwise returns false.

In the example above, we do this:

@Override Public 
Boolean isviewfromobject (View arg0, Object arg1) { 
  //TODO auto-generated method stub 
  return arg0 = = Arg1; 
 

As in Instantiateitem (), we return the current view as key, so when we judge here, we directly judge whether the key and view are equal to the same view.

V. Custom Key Instances
after the above explanation, presumably everyone to the concept of key should have a clear understanding of the following example to illustrate the relationship between key and view, because key and view to one by one, so I put the position of each view position as a key, in the previous chapter of the example based on the change , look at the entire code, and then look at some of the explanations:

Package com.example.testviewpage_2; 
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.LayoutInflater; 
Import Android.view.View; 
 
Import Android.view.ViewGroup; 
  public class Mainactivity extends activity {private View view1, View2, VIEW3; Private list<view> viewlist;//View array private Viewpager Viewpager; The corresponding Viewpager @Override protected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstance 
    State); 
    Setcontentview (R.layout.activity_main); 
    Viewpager = (Viewpager) Findviewbyid (R.id.viewpager); 
    Layoutinflater inflater = Getlayoutinflater (); 
    View1 = inflater.inflate (R.LAYOUT.LAYOUT1, NULL); 
    View2 = inflater.inflate (r.layout.layout2, NULL); 
 
    VIEW3 = inflater.inflate (R.LAYOUT.LAYOUT3, NULL); Viewlist = new arraylist<view> ()//Will bePage display view mount array viewlist.add (VIEW1); 
    Viewlist.add (VIEW2); 
 
    Viewlist.add (VIEW3); Pageradapter pageradapter = new Pageradapter () {@Override public boolean isviewfromobject (View arg0, Obje CT arg1) {//TODO auto-generated method Stub//According to the key that came in, find view, judge with the argument that came from view arg0 is not the same view retur 
      n arg0 = = Viewlist.get ((int) integer.parseint (arg1.tostring ())); @Override public int GetCount () {//TODO auto-generated a stub return Viewlist.s 
      Ize (); 
        @Override public void Destroyitem (ViewGroup container, int position, object object) { 
      TODO auto-generated Method Stub Container.removeview (Viewlist.get (position)); @Override public Object Instantiateitem (viewgroup container, int position) {//TODO Auto-gener 
 
        Ated method Stub Container.addview (Viewlist.get (position)); Position the current new view (position) as a KeY pass past return position; 
 
    } 
    }; 
 
  Viewpager.setadapter (Pageradapter); 
 } 
 
}

Two places were changed here:
1, first look at the location of the key Instantiateitem ()

@Override public 
Object instantiateitem (viewgroup container, int position) { 
  //TODO auto-generated method stub< C4/>container.addview (Viewlist.get (position)); 
 
  The current new view position (position) as key pass return 
  position; 


We also talked about the key in this function as the return value corresponds to the view in the current Mount container. So here we go back to postion and Container.addview (viewlist.get (position)), the Viewlist.get (position) in this view corresponds.
2, Isviewfromobject ()

@Override Public 
Boolean isviewfromobject (View arg0, Object arg1) { 
  //TODO auto-generated a stub 
  // According to the key, find the view, judge with the argument that came to view arg0 is not the same view return 
  arg0 = = Viewlist.get ((int) integer.parseint (arg1.tostring ()) ; 
} 

Judging from the Instantiateitem () returned key and the current view can correspond, we know from the Instantiateitem passed over is actually position, so we have to according to position find view, And then with the argument in the View arg0 judge.

However, when there is a problem with the real operation, we first convert the obect to type int: (int) integer.parseint (arg1.tostring ()), and then find the corresponding view according to position;

Effect diagram: Sliding switch between three view

This is only so unlike the previous chapter, only a part of the last part of the slide switch, because I changed the layout file:

<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 " 
  tools:context= "com.example.testviewpage_2.MainActivity" > 
 
  <android.support.v4.view.viewpager 
    android:id= "@+id/viewpager" 
    android:layout_width= "wrap_content" 
    android:layout_height= "200dip" 
    android:layout_gravity= "center"/> 
 
</RelativeLayout> 

Here will be layout_height to 200dip, only so do, is to tell you, as long as you want to achieve sliding switch place add <android.support.v4.view.viewpager/> can switch, No matter the position and the size, like the normal control!!!!!!

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.