Automatic switching of Viewpager pages using handler in Android app _android

Source: Internet
Author: User
Tags object object

In many Electronic business Web pages and apps have automatic switching of merchandise to promote fast, feeling very good experience, just today to learn to use Viewpager, so also implemented a similar function of the demo.

Here are two screenshots:

To achieve an automatic playback function of the Viewpager, there are mainly the following parts:

Implement a viewpageradapter to provide presentation content for Viewpager (for example, two kitten pictures above)

 public class Viewpageradapter extends Pageradapter {
    private list<view> mdata;
    Public Viewpageradapter (list<view> mdata) {
      this.mdata = mdata;
    }

    @Override public
    int GetCount () {return
      mdata.size ();
    }

    @Override Public
    Boolean isviewfromobject (View arg0, Object arg1) {return
      arg0 = = arg1;
    }
    
    @Override public
    Object instantiateitem (viewgroup container, int position) {
      View v = mdata.get (position); C16/>container.addview (v);
      return v;
    }
    
    @Override public
    void Destroyitem (ViewGroup container, int position, object object) {
//  Super.destroyitem (container, Position, object);
      Container.removeview (Mdata.get (position));
    }
    
  

Implement a onpagechangelistener so that when the page is switched, you can prompt the current page's position (for example, the 3 dots in the lower left corner of the image above, the red represents the current page)

 Private class Viewpagechangelistener implements Onpagechangelistener {

    @Override public
    Void onpagescrollstatechanged (int arg0) {
    }

    @Override public
    void onpagescrolled (int arg0, float arg1, int arg2) {
    }

    //Monitor page Change event to change the indication picture in Viewindicator
    @Override public
    void onpageselected (int arg0) {
      int len = Viewindicator.getchildcount ();
      for (int i = 0; i < len; ++i)
        Viewindicator.getchildat (i) Setbackgroundresource (r.drawable.tip_normal);
      Viewindicator.getchildat (arg0). Setbackgroundresource (R.drawable.tip_select);
    }
    
  

Implements a handler for modifying the UI after a certain interval (switching the currently displayed picture to the next)

Private Handler Mhandler = new Handler () {public
    void Handlemessage (Android.os.Message msg) {
      switch (msg.what) { Case
      1:
        int totalcount = Pagers.size ();//autochangeviewpager.getchildcount ()
        ; int currentitem = Autochangeviewpager.getcurrentitem ();
        
        int Toitem = CurrentItem + 1 = totalcount? 0:currentitem + 1;
        
        LOG.I (TAG, "totalcount:" + totalcount + "  currentitem:" + CurrentItem + "  toitem:" + toitem);
        
        Autochangeviewpager.setcurrentitem (Toitem, true);
        
        Send a message every two seconds to toggle the picture in Viewpager
        this.sendemptymessagedelayed (1);
      }}
  ;


The above 3 paragraphs are the main code, in addition to the need to send a starting message in Onresume () and OnStop () to stop the Viewpager page of the automatic switching and so on.
The complete code is as follows:

public class Mainactivity extends activity {private static final String TAG = MainActivity.class.getSimpleName ();
  
  Private Viewpager Autochangeviewpager;
  
  Used to indicate where the current display picture is located private LinearLayout viewindicator;
  Contains pictures to display in Viewpager private list<view> pagers;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    
    Setcontentview (R.layout.activity_main);
    Autochangeviewpager = (Viewpager) Findviewbyid (R.ID.AUTOVP);
    
    Viewindicator = (linearlayout) Findviewbyid (r.id.vpindicator);
    
    Initadapter ();
    
  Monitor page change events to change the Viewindicator in the Autochangeviewpager.setonpagechangelistener (New Viewpagechangelistener ()); private void Initadapter () {//Viewpager picture resources to be displayed in the int[] IMGs = {r.drawable.i1, r.drawable.i2, r.drawable.
    
    i3};
    Init pagers;
    pagers = new arraylist<view> (); Linearlayout.layoutparams img_params = new Layoutparams (LAYOUTPARAMS.MATCH_parent, layoutparams.match_parent);
      for (int i = 0; i < imgs.length. ++i) {ImageView IV = new ImageView (this);
      Iv.setbackgroundresource (Imgs[i]);
      Iv.setlayoutparams (Img_params);
      Final int index = i; Iv.setonclicklistener (New Onclicklistener () {///when the picture in Viewpager is clicked, jumps to the @Override public
          void OnClick (View v) {Intent i = new Intent (mainactivity.this, Invokedactivity.class);
          I.putextra ("name", "cat" + index);
        MainActivity.this.startActivity (i);
      }
      });
    Pagers.add (iv);
    
    } autochangeviewpager.setadapter (New Viewpageradapter (pagers)); Init indicator Linearlayout.layoutparams ind_params = new Layoutparams (layoutparams.wrap_content, LayoutPar Ams.
    Wrap_content);
      for (int i = 0; i < imgs.length. ++i) {ImageView IV = new ImageView (this);
      if (i = = 0) iv.setbackgroundresource (r.drawable.tip_select);else Iv.setbackgroundresource (r.drawable.tip_normal);
      Iv.setlayoutparams (Ind_params);
    Viewindicator.addview (iv);
    }} @Override protected void Onresume () {super.onresume ();
  The activity starts two seconds later, sending a message to switch the picture in the Viewpager to the next mhandler.sendemptymessagedelayed (1, 2000);
    } @Override protected void OnStop () {super.onstop ();
  Stop the Automatic switching mhandler.removemessages (1) of the picture in Viewpager;
    public class Viewpageradapter extends Pageradapter {private list<view> mdata;
    Public Viewpageradapter (list<view> mdata) {this.mdata = Mdata;
    @Override public int GetCount () {return mdata.size ();
    @Override public boolean isviewfromobject (View arg0, Object arg1) {return arg0 = = Arg1; @Override public Object Instantiateitem (viewgroup container, int position) {View v = mdata.get (posit
      ION);
      Container.addview (v);
    return v; } @Override
    public void Destroyitem (ViewGroup container, int position, object object) {//Super.destroyitem (container, Position
      , object);
    Container.removeview (Mdata.get (position)); The private class Viewpagechangelistener implements Onpagechangelistener {@Override public void Onpa
    gescrollstatechanged (int arg0) {} @Override public void onpagescrolled (int arg0, float arg1, int arg2) { //Listen for page change events to change the instructions in viewindicator @Override public void onpageselected (int arg0) {int len = Viewindi
      Cator.getchildcount ();
      for (int i = 0; i < len; ++i) Viewindicator.getchildat (i) Setbackgroundresource (r.drawable.tip_normal);
    Viewindicator.getchildat (arg0). Setbackgroundresource (R.drawable.tip_select); } private Handler Mhandler = new Handler () {public void Handlemessage (Android.os.Message msg) {s Witch (msg.what) {case 1:int totalcount = Pagers.size ();//autochangeviewpager.getChildCount ();
        
        int currentitem = Autochangeviewpager.getcurrentitem (); int Toitem = CurrentItem + 1 = totalcount?
        
        0:currentitem + 1;
        
        LOG.I (TAG, "totalcount:" + TotalCount + "CurrentItem:" + CurrentItem + "Toitem:" + Toitem);
        
        Autochangeviewpager.setcurrentitem (Toitem, true);
      Send a message every two seconds to toggle the picture in Viewpager this.sendemptymessagedelayed (1, 2000);
}
    }
  };

 }

The layout file is as follows: (The invokedactivity in the code above is very simple, omitted here)

<framelayout xmlns:android= "http://schemas.android.com/apk/res/android"
  android:layout_width= "Match_ Parent "
  android:layout_height=" match_parent ">

  <android.support.v4.view.viewpager
    android:id= "@+id/autovp"
    android:layout_width= "match_parent"
    android:layout_height= "match_parent"/>

  < LinearLayout
    android:id= "@+id/vpindicator"
    android:layout_width= "match_parent"
    android:layout_ height= "Wrap_content"
    android:layout_gravity= "bottom" android:orientation= "horizontal"
    />

</FrameLayout>

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.