Android with handler for automatic switching of pages in Viewpager

Source: Internet
Author: User

In many e-commerce Web pages and apps have automatic switching of products to promote fast, feel very good experience, just today learning to use Viewpager, so also implemented a similar function of the demo.

Here are two of them:

To achieve an auto-play function of the Viewpager, to do the main has the following several parts:

    • Implement a viewpageradapter to provide display content for Viewpager (e.g. two kitten pictures above)
public class Viewpageradapter extends Pageradapter {private list<view> mdata;public viewpageradapter (list< View> mdata) {this.mdata = Mdata;} @Overridepublic int GetCount () {return mdata.size ();} @Overridepublic boolean isviewfromobject (View arg0, Object arg1) {return arg0 = = arg1;} @Overridepublic Object Instantiateitem (viewgroup container, int position) {View v = mdata.get (position); Container.addview (v); return v;} @Overridepublic void Destroyitem (ViewGroup container, int position, object object) {//super.destroyitem (container, Position, object); Container.removeview (Mdata.get (position));}}

    • Implement a Onpagechangelistener, so that after the page switch can prompt the current page location (for example, 3 dots in the lower left corner, red indicates the current page)
Private class Viewpagechangelistener implements Onpagechangelistener {@Overridepublic void onpagescrollstatechanged ( int arg0) {} @Overridepublic void onpagescrolled (int arg0, float arg1, int arg2) {}// Listen for page change events to change the viewindicator in the indicator picture @overridepublic 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 that modifies the UI after a certain interval (the currently displayed picture is switched 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); autochangeviewpage R.setcurrentitem (Toitem, true);//Send a message every two seconds to toggle the picture this.sendemptymessagedelayed (1, 2000) in Viewpager;}};

The above 3 paragraphs are the main code, and in addition, you need to send a starting message in Onresume () and stop the automatic switching of the Viewpager page in OnStop ().

The complete code is as follows:

public class Mainactivity extends Activity {private static final String TAG = MainActivity.class.getSimpleName ();p rivate V Iewpager autochangeviewpager;//used to indicate the location of the currently displayed picture private LinearLayout viewindicator;//contains the picture to be displayed in Viewpager private List <View> pagers, @Overrideprotected 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 ();// Listen for the page change event to change the indicator image in Viewindicator autochangeviewpager.setonpagechangelistener (New Viewpagechangelistener ());} private void Initadapter () {//Picture resources to be shown in Viewpager 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, jump to the new activity@overridepublic 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 Indicatorlinearlayout.layoutparams Ind_params = new Layoutparams (layoutparams.wrap_content, layoutparams.wrap_content); for (int i = 0; i < imgs.length; ++i) {ImageVi EW IV = new ImageView (this), if (i = = 0) iv.setbackgroundresource (r.drawable.tip_select); Elseiv.setbackgroundresource ( R.drawable.tip_normal); Iv.setlayoutparams (ind_params); Viewindicator.addview (iv);}} @Overrideprotected void Onresume () {super.onresume ();//activity starts two seconds, sends a message, Used to switch the picture in Viewpager to the next mhandler.sendemptymessagedelayed (1, 2000);} @Overrideprotected void OnStop () {super.onstop ();//stop automatic switching of pictures in Viewpager Mhandler.removemEssages (1);} public class Viewpageradapter extends Pageradapter {private list<view> mdata;public viewpageradapter (list< View> mdata) {this.mdata = Mdata;} @Overridepublic int GetCount () {return mdata.size ();} @Overridepublic boolean isviewfromobject (View arg0, Object arg1) {return arg0 = = arg1;} @Overridepublic Object Instantiateitem (viewgroup container, int position) {View v = mdata.get (position); Container.addview (v); return v;} @Overridepublic void Destroyitem (ViewGroup container, int position, object object) {//super.destroyitem (container, Position, object); Container.removeview (Mdata.get (position));}} Private class Viewpagechangelistener implements Onpagechangelistener {@Overridepublic void onpagescrollstatechanged ( int arg0) {} @Overridepublic void onpagescrolled (int arg0, float arg1, int arg2) {}// Listen for page change events to change the viewindicator in the indicator picture @overridepublic 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);}} 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.se Tcurrentitem (Toitem, true);//A message is sent every two seconds to toggle the picture this.sendemptymessagedelayed (1, 2000) in the Viewpager;}};}

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>

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.