Android Viewpager to make novice navigation page (dynamic load) _android

Source: Internet
Author: User
Tags object object

We talk about a commonplace topic, estimated that everyone used the->viewpager, use it to do the novice navigation page, although this is also about this, but the use of the past may be a little different, we all see the title came in, should know: dynamic load indicator.

What is called dynamic loading, is not feeling very tall, in fact, it is dynamic to load the number of indicators, rather than in the layout file to write dead. Hope to read this article you have a new understanding of Viewpager.

See this effect everyone should be very disdain it, today to say this is to let everyone have a new understanding. All right, listen up, let's go.

This dynamic loading is to dynamically load the following gray dot indicator and red dot indicator, and everyone has noticed that when I slide (that is, when the page is switched) The red dots will move along. That's right.

First step:

Add Viewpager to the layout file, and add gray dots and red dots layout, first think about what the layout, first three gray dots can be linear layout, a red dot can use relative layout (reason: In fact, red dot is covered with gray dots)

 <relativelayout
    android:id= "@+id/rl"
    android:layout_width= "wrap_content"
    android:layout_height= "Wrap_content"
    android:layout_alignparentbottom= "true"
    android:layout_centerhorizontal= "true"
    android:layout_marginbottom= "30DP" >
    <!--Gray dot layout-->
    <linearlayout
      android:id= "@+id/ll"
      android:layout_width= "wrap_content"
      android:layout_height= "wrap_content"
      android:orientation= " Horizontal ">
    </LinearLayout>    
  </RelativeLayout>

Step Two:

An example of declaring viewpager and gray dots and red dot layouts in the OnCreate method (reason: Because we need to load the dots dynamically) and adding adapters and listeners for Viewpager.

  Viwepager
  private Viewpager Viewpager;
  A linear layout of three gray dots is stored
  private linearlayout ll;
  The relative layout used to store red dots and gray dots
  private relativelayout RL;
  Initialize the component
  private void Initview () {
    Viewpager = (viewpager)   Findviewbyid (R.id.viewpager);
    Imageviews = new arraylist<imageview> ();
    ll = (linearlayout) Findviewbyid (R.ID.LL);
    RL = (relativelayout) Findviewbyid (R.ID.RL);
    BTN = (Button) Findviewbyid (R.ID.BTN);
  Add Adapter Viewpager.setadapter to Viewpager (
  new Myadapter ());
  Viewpager.setonpagechangelistener ();

Step Three:

Add three pictures to the Viewpager adapter.

Note: in order to not duplicate the creation of picture instances while sliding, we can save system resources by first placing the resource that needs to be loaded in a set and removing it from the collection each time the slide needs to be loaded.

Navigation page Resources Private int[] images = new int[]{r.drawable.guide_1, r.drawable.guide_2, R.drawable.guide_3,};
    Used to store navigation picture instances (guaranteed uniqueness, sliding without duplicating creation) private list<imageview> imageviews;
      Initializes the navigation page for (int i = 0; i < images.length i++) {ImageView IV = new ImageView (mainactivity.this);
      Iv.setimageresource (Images[i]);
    Imageviews.add (iv); //pageradapter has four methods class Myadapter extends Pageradapter {//returns the number of navigation pages @Override public int GetCount ()
    {return images.length; //Judge whether the object is generated @Override public boolean isviewfromobject (View View,object object) {return view = = Object
    ; //Load page//viewgroup: Parent control refers to Viewpager//position: The position of the current child control in the parent control @Override public Object Instantiateitem (Vi
      Ewgroup container, int position) {ImageView IV = imageviews.get (position);
      Container.addview (iv);
    return IV; //Remove page @Override public void Destroyitem (ViewGroup container, INT position, Object object) {Container.removeview (View) object); }
  }

Fourth Step:

The important part is that the step is to dynamically add gray dots and red dots and let the red dots slide along with the slide.

First, add the gray dots and red dots dynamically:

for (int i = 0; i < images.length i++) {
      ImageView IV = new ImageView (mainactivity.this);
      Iv.setimageresource (Images[i]);
      Imageviews.add (iv);
      Dynamic load Gray dot
      imageview Gray_iv = new ImageView (this);
      Gray_iv.setimageresource (r.drawable.grar_circle);
      Linearlayout.layoutparams layoutparams = 
          new Layoutparams (layoutparams.wrap_content,
              LAYOUTPARAMS.WRAP_ CONTENT);
      There is a margin
      if (i > 0) {
        layoutparams.leftmargin = m from the second start;  Attention unit is PX
      }
      gray_iv.setlayoutparams (layoutparams);
      Ll.addview (GRAY_IV);
    }
    Add red dot
    Red_iv = new ImageView (this);
    Red_iv.setimageresource (r.drawable.red_circle);
    Rl.addview (RED_IV);

Note: The gray dot is from the second to have the left margin, for the component dynamic set margin words using the layout of the Layoutparams (clothing), remember three gray dots using which layout is used in that layout of the layoutparams to set.

The following is to let the red dots slide along with the Viewpager and then slide together:

//any one component can get the View Tree Red_iv.getviewtreeobserver (). Addongloballayoutlistener (New When the Ongloballayoutlistener () {//view finishes drawing, it calls @Override public void Ongloballayout () {left = Ll.getc
        Hildat (1). GetLeft ()-ll.getchildat (0). GetLeft ();
        System.out.println (left);
      Removes the Listener red_iv.getviewtreeobserver () Removeglobalonlayoutlistener (this) from the view tree.
    }
    }); Call//positionoffset when the navigation page slides: The percentage of sliding ([0,1}) @Override public void onpagescrolled (int position, float POS Itionoffset, int arg2) {Relativelayout.layoutparams layoutparams = (relativelayout.layoutparams) red_Iv.getLayout
        Params ();
        Layoutparams.leftmargin = (int) (left * positionoffset + position * left);
      Red_iv.setlayoutparams (Layoutparams); }

Note: Here we need to understand a concept –> view tree, why understand this, because we are dynamic to add gray dots, do not know what the view can be drawn, so you need to listen to the entire view of the drawing state, any one component can get to the view tree, Monitor the rendering of the view tree. So you can get the distance between the gray dots, we will ask the beginning to add gray dot when the left margin is not set??? Yes, but this unit is PX, and now the DP cannot be set directly.

The distance between gray dots:

left = Ll.getchildat (1). GetLeft ()-ll.getchildat (0). GetLeft ();
parameters in the public void onpagescrolled (int position, float positionoffset, int arg2) Positionoffset The percentage of the sliding (range [0-1))

Now you know how much the red dots need to slide.

      Call//positionoffset when the navigation page slides
      : The percentage of sliding ([0,1))
      @Override public
      void onpagescrolled (int position, float Positionoffset, int arg2) {
        Relativelayout.layoutparams layoutparams = (relativelayout.layoutparams) red_ Iv.getlayoutparams ();
        Layoutparams.leftmargin = (int) (left * positionoffset + position * left);
        Red_iv.setlayoutparams (Layoutparams);
      }

Fifth Step:

Novice navigation page, generally moved to the last page when there will be a button to jump to the main interface. This only needs to be set when the navigation page is selected

When the navigation page is selected
      , call @Override public
      void onpageselected (int position) {
        //slide to the last page, display the button
        if (position = = images.length-1) {
          btn.setvisibility (view.visible);
        is not the last page, the button is not displayed
        }else {
          btn.setvisibility (view.gone);
        }
      

Core code:

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.viewpager.MainActivity" > <android.support.v4.view.viewpager android:id= "@+id/viewpager" an Droid:layout_width= "Match_parent" android:layout_height= "match_parent" > </ android.support.v4.view.viewpager> <relativelayout android:id= "@+id/rl" android:layout_width= "Wrap_conten" T "android:layout_height=" Wrap_content "android:layout_alignparentbottom=" true "Android:layout_centerhorizonta L= "true" android:layout_marginbottom= "30DP" > <!--Gray dot layout--> <linearlayout android:id= "@+id/ ll "android:layout_width=" Wrap_content "android:layout_height=" wrap_content "android:orientation=" Horizo Ntal "> </LinearLayout> </RelativeLayout> <button ANdroid:layout_width= "Wrap_content" android:id= "@+id/btn" android:layout_alignparentbottom= "true" android:layou T_centerhorizontal= "true" android:layout_marginbottom= "50DP" android:layout_height= "Wrap_content" Android:tex

 T= "Experience" android:visibility= "Gone"/> </RelativeLayout>

Mainactivity.java

public class Mainactivity extends activity {//viwepager private viewpager viewpager;
  Private Button btn;
  Navigation page Resources Private int[] images = new int[]{r.drawable.guide_1, r.drawable.guide_2, R.drawable.guide_3,};
  The margin between the dot and the dot is private int left;
  Used to store navigation picture instances (guaranteed uniqueness, sliding without duplicating creation) private list<imageview> imageviews;
  A linear layout of three gray dots is stored private linearlayout ll;
  The relative layout used to store red dots and gray dots private relativelayout RL;
  Red dot ImageView private ImageView Red_iv;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main);
    Initview ();
      Initializes the navigation page and gray dot for (int i = 0; i < images.length i++) {ImageView IV = new ImageView (mainactivity.this);
      Iv.setimageresource (Images[i]);
      Imageviews.add (iv);
      Dynamic load Gray dot ImageView Gray_iv = new ImageView (this);
      Gray_iv.setimageresource (r.drawable.grar_circle); Linearlayout.layoutparams LayOutparams = new Layoutparams (layoutparams.wrap_content, layoutparams.wrap_content);  From the second start there is margin if (i > 0) {layoutparams.leftmargin = 20;
      Attention unit is PX} gray_iv.setlayoutparams (Layoutparams);
    Ll.addview (GRAY_IV);
    } Red_iv = new ImageView (this);
    Red_iv.setimageresource (r.drawable.red_circle);
    Rl.addview (RED_IV); Any one component can get the View Tree Red_iv.getviewtreeobserver (). Addongloballayoutlistener (The new Ongloballayoutlistener () {//view finishes drawing @Override public void Ongloballayout () {left = Ll.getchildat (1) is called. GetLeft ()-ll.getchildat (0). Get
        Left ();
        System.out.println (left);
      Removes the Listener red_iv.getviewtreeobserver () Removeglobalonlayoutlistener (this) from the view tree.
    }
    });
    Add Adapter Viewpager.setadapter to Viewpager (new Myadapter ()); Viewpager.setonpagechangelistener (New Onpagechangelistener () {//Navigation page is selected when called @Override public void Onpag eselected (int position) {if (position = = images.length-1) {btn.setvisibility (view.visible);
        }else {btn.setvisibility (view.gone); }///navigation page sliding when calling//positionoffset: sliding percent ([0,1}) @Override public void onpagescrolled (int pos Ition, float positionoffset, int arg2) {Relativelayout.layoutparams layoutparams = (relativelayout.layoutparams)
        Red_iv.getlayoutparams ();
        Layoutparams.leftmargin = (int) (left * positionoffset + position * left);
      Red_iv.setlayoutparams (Layoutparams);
  }//Navigation page sliding state changes when called @Override public void onpagescrollstatechanged (int arg0) {}});
    }//Initialize component private void Initview () {Viewpager = (Viewpager) Findviewbyid (R.id.viewpager);
    Imageviews = new arraylist<imageview> ();
    ll = (linearlayout) Findviewbyid (R.ID.LL);
    RL = (relativelayout) Findviewbyid (R.ID.RL);
  BTN = (Button) Findviewbyid (R.ID.BTN); //pageradapter has four methods clAss Myadapter extends Pageradapter {//returns the number of navigation pages @Override public int GetCount () {return images.length; //Judge whether the object is generated @Override public boolean isviewfromobject (View View,object object) {return view = = OB
    ject; //Load page//viewgroup: Parent control refers to Viewpager//position: The position of the current child control in the parent control @Override public Object Instantiateitem (Vi
      Ewgroup container, int position) {ImageView IV = imageviews.get (position);
      Container.addview (iv);
    return IV; //Remove page @Override public void Destroyitem (ViewGroup container, int position, object object) {container
    . Removeview ((View) object);

 }
  }
}

Let's try it quickly. will have a different understanding.

This is the entire content of this article, I hope to learn more about Android software programming help.

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.