Android Viewpager realizes the marquee switch picture + various toggle animations

Source: Internet
Author: User

Recently in a project to request a photo display of the effect of a marquee. Online Search a bunch, have no perfect realization of forget or write it yourself!

Implementing the principle of using the Viewpager control, the control itself supports sliding page flipping is very good and powerful many functions can use it. Use of Mviewpager.setcurrentitem (Currentindex); To toggle the currently displayed view

In addition a timer constantly set Setcurrentitem to achieve the marquee effect.

One. Main implementation class annotations in a very detailed look, I know.

Package Com.example.marqueeimage;import Java.lang.reflect.field;import Java.util.arraylist;import Java.util.Timer; Import Java.util.TimerTask; Import Com.example.marqueeimage.adapter.marqueeadapter;import Com.example.marqueeimage.transforms.ABaseTransformer; Import Android.annotation.SuppressLint;  Import Android.content.Context; Import Android.os.handler;import Android.os.message;import Android.support.v4.view.viewpager;import Android.support.v4.view.viewpager.onpagechangelistener;import Android.util.attributeset;import Android.view.layoutinflater;import Android.view.motionevent;import Android.view.View;  Import Android.view.ViewGroup; Import Android.view.animation.AccelerateInterpolator; Import Android.widget.imageview;import Android.widget.linearlayout;public class Marqueeimage extends LinearLayout{ Private Viewpager mviewpager;private arraylist<view> mpageviewlist=new arraylist<view> ();//data?? Private ImageView mimageview;private imageview[] mimageviews;//main cloth???? Indicates the small dots on the current page, depending on theFigure, Linearlayoutprivate viewgroup indicatorviewgroup;private layoutinflater minflater;//definition Layoutinflaterprivate Marqueeadapter marqueeadapter;//suitable for the match?? Private timer mtimer=null;//timing?? public int currentindex=0;//currently displays the sequence number of the view page private Handler mhandler;//processing the change picture message private Fixedspeedscroller Scroller=null ;p rivate Context Mcontext;public marqueeimage (context context) {super (context); init (context);}     Public Marqueeimage (context context, AttributeSet Attrs) {Super (context, attrs); init (context);}    private void init (context context) {Mcontext=context; Layoutinflater.from (Mcontext). Inflate (r.layout.marquee_image, this); Mviewpager = (Viewpager) findViewById (    R.id.marquee_image_viewpager);    Indicatorviewgroup = (viewgroup) Findviewbyid (R.id.marquee_image_bottomviewgroup);    Mviewpager.setonpagechangelistener (New Pagechangelistener ()); Mviewpager.setontouchlistener (New Ontouchlistener () {@Overridepublic Boolean onTouch (View V, motionevent event) {if ( Event.getaction () ==motionevent.action_down){Stopautoscroller (); Setscrollertime (100); }else if (event.getaction () ==motionevent.action_up) {Startautoscroller ();}     return false;}});     Marqueeadapter=new Marqueeadapter (); Mviewpager.setadapter (Marqueeadapter); Inithandle ();    }/** * Set slide animation * Mviewpager.setpagetransformer (True,new cubeouttransformer ());    Mviewpager.setpagetransformer (True,new Accordiontransformer ());    Mviewpager.setpagetransformer (True,new Fliphorizontaltransformer ());    Mviewpager.setpagetransformer (True,new Rotateuptransformer ());    Mviewpager.setpagetransformer (True,new Zoomouttranformer ());    Mviewpager.setpagetransformer (True,new Zoomoutslidetransformer ());     Mviewpager.setpagetransformer (True,new Tablettransformer ());    */public void setscrolleranimation (Abasetransformer animation) {Mviewpager.setpagetransformer (true,animation);    }/** * Starts auto-scrolling */public boolean Startautoscroller () {return startTime (); }/** * Stop auto-scrolling */publicBoolean Stopautoscroller () {if (mtimer!=null) {mtimer.cancel ();        Mtimer=null;    return true;    }else{return false; }}/** * Initialize handle */public void Inithandle () {Mhandler = new Handler () {@SuppressLint ("Newapi") public void Handlem Essage (Message msg) {if (msg.what==1) {setscrollertime); Mviewpager.setcurrentitem (currentindex); if (MPAGEVIEWL Ist.size () -1==currentindex) {currentindex=0;}   else{currentindex++;}  } }; };} /** * Set sliding time */public void setscrollertime (int scrollertime) {try {if (scroller!=null) {scroller.settime (Scrollertime)}            Else{field Mscroller;            Mscroller = ViewPager.class.getDeclaredField ("Mscroller");             Mscroller.setaccessible (TRUE);            scroller= New Fixedspeedscroller (Mviewpager.getcontext (), New Accelerateinterpolator ());            Scroller.settime (Scrollertime);         Mscroller.set (Mviewpager, scroller);} } catch (Exception e) {}}/** * creates the bottom navigation bar */public void CreatenavBar () {mimageviews = new imageview[mpageviewlist.size ()]; for (int i = 0; i < mimageviews.length; i++) {Mimagev          Iew = new ImageView (mcontext);          Mimageview.setlayoutparams (New Layoutparams (20,20));           Mimageview.setpadding (20, 0, 20, 0); if (i = = 0) {mimageview.setbackgroundresource (r.drawable.page_indicator_focused);} else {Mimageview.setbackgroundr        Esource (r.drawable.page_indicator);}                Mimageviews[i] = Mimageview; Indicatorviewgroup.addview (Mimageviews[i]) to add a far-point image of the indicator to the bottom view;} }class Pagechangelistener implements onpagechangelistener{@Overridepublic void onpageselected (int arg0) {//TODO Auto-generated method Stubfor (int i = 0; i < mimageviews.length; i++) {if (i = = arg0) {Mimageviews[i].setbackgroundreso Urce (r.drawable.page_indicator_focused);} else {mimageviews[i].setbackgroundresource (r.drawable.page_indicator);}} } @Overridepublic void onpagescrolled (int arg0, float arg1, int arg2) {//TODO auto-generated MeThod stub} @Overridepublic void onpagescrollstatechanged (int arg0) {//TODO auto-generated Method stub}}/** * Start timing *   /Private Boolean startTime () {if (mtimer==null) {Mtimer = new Timer (); Mtimer.schedule (New TimerTask () {@Override public void run () {Message msg=n         EW Message (); Msg.what=1;mhandler.sendmessage (msg); }},2000,2000);   Executes the return true every 2 seconds;   }else{return false; }}/** * Set data * @param mpageviews */public void SetData (arraylist<view> pageviewlist) {if (Pageviewli  St!=null) {this.mpageviewlist=pageviewlist;  Marqueeadapter.setdata (mpageviewlist);//Add Data marqueeadapter.notifydatasetchanged ();//notification data changes??   Createnavbar ();//Based on data, create a navigation bar}}/** * Clean up all data */public void ClearData () {if (this.mpageviewlist!=null) {   This.mPageViewList.clear ();  } mviewpager.removeallviews ();   Indicatorviewgroup.removeallviews (); }}
two. The Viewpager adapter is also very simple

Package Com.example.marqueeimage.adapter;import Java.util.arraylist;import Android.os.parcelable;import Android.support.v4.view.pageradapter;import android.support.v4.view.viewpager;import android.view.View;/** * @ Author FCM * @Create at 2013-8-27 pm 2:48:34 * @Version 1.0 * <p>features Draft description. Main Features </p> */pub Lic class Marqueeadapter extends Pageradapter{private arraylist<view> mpageviews=new arraylist<view> ();/* * * Add Data * @param mpageviews */public void SetData (arraylist<view> mpageviews) {this.mpageviews=mpageviews;}      @Override public int GetCount () {return mpageviews.size ();      } @Override public boolean isviewfromobject (View arg0, Object arg1) {return arg0 = = Arg1; } @Override public int getitemposition (Object object) {//TODO auto-generated method stub ret      Urn Super.getitemposition (object); } @Override public void Destroyitem (View arg0, int arg1, Object arg2{//TODO auto-generated Method Stub ((Viewpager) arg0). Removeview (Mpageviews.get (arg1));          } @Override Public Object instantiateitem (View arg0, int arg1) {//TODO auto-generated method stub          ((Viewpager) arg0). AddView (Mpageviews.get (arg1));      Return Mpageviews.get (ARG1);  } @Override public void Restorestate (parcelable arg0, ClassLoader arg1) {//TODO auto-generated method stub} @Override public Parcelable saveState () {//TODO auto-generated method stub Retu      RN null; } @Override public void Startupdate (View arg0) {//TODO auto-generated method stub} @Overri De public void Finishupdate (View arg0) {//TODO auto-generated method stub}}
three. It's important to control the sliding speed. Set automatic scrolling The default speed is very poor, with Fixedspeedscroller inheriting scroller to control viewpaper sliding speed This part comes from the network

Package Com.example.marqueeimage;import Android.annotation.suppresslint;import Android.content.context;import Android.view.animation.interpolator;import Android.widget.scroller;public class Fixedspeedscroller extends Scroller        {private int mduration = 500;    public void settime (int scrollertime) {mduration=scrollertime;    } public Fixedspeedscroller (context context) {super (context);    } public Fixedspeedscroller (context context, Interpolator Interpolator) {Super (context, interpolator);        } @SuppressLint ("Newapi") public Fixedspeedscroller (context context, Interpolator interpolator, Boolean flywheel) {    Super (context, interpolator, flywheel); } @Override public void startscroll (int startX, int starty, int dx, int dy, int duration) {//Ignore receive    d duration, use fixed one instead super.startscroll (StartX, starty, dx, DY, mduration); } @Override public void startscroll (int startX, int starty, int dx, int dy) {        Ignore received duration, use fixed one instead super.startscroll (StartX, starty, dx, DY, mduration); }}
Four. Layout file:

<?xml    Version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"    Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:id= "@+id/marquee_image_layout" android:orientation= "Vertical" > <!--drag-and-<android.support.v4.view.viewpager android:id= "@+i D/marquee_image_viewpager "android:layout_width=" wrap_content "android:layout_height=" 0DP "Android:la yout_weight= "1"/> <linearlayout android:id= "@+id/marquee_image_bottomviewgroup" Android:la Yout_width= "Fill_parent" android:layout_height= "wrap_content" android:gravity= "Center_horizontal" a ndroid:orientation= "Horizontal" > </LinearLayout> </linearlayout> 
Five. The final step is to modify the default animation to achieve a more brilliant effect this part from the network about 10 kinds of animation bar

Source: http://download.csdn.net/download/nn955/7465547

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.