Android Viewpager realizes the marquee switch picture + various toggle animations

Source: Internet
Author: User
Tags stub

I'm getting a project recently. A picture showing the effect of a marquee is required.

Online Search a bunch, have no perfect realization of forget or write it yourself!

The implementation principle utilizes the Viewpager control, which natively supports sliding page flipping, which is very good, very powerful, and it can be used for many functions. Use of Mviewpager.setcurrentitem (Currentindex); To toggle the currently displayed view

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

One. The main realization class gaze is very specific.

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??

?? section indicates the small dot view of the current page, linearlayoutprivate viewgroup indicatorviewgroup;private layoutinflater minflater;// Define Layoutinflaterprivate marqueeadapter marqueeadapter;//adaptation??

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 its own active scrolling */public boolean Startautoscroller () {return startTime (); }/** * Stop itself active scrolling */public boolean 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.s Ize ()]; for (int i = 0; i < mimageviews.length; i++) {Mimageview = 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 Timer */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); Run once every 2 seconds to return true; }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 navigation Bar}}/** * Clean up all data */public void ClearData () {if (this.mpageviewlist!=null) {this.mPageViewList.cle AR (); } mviewpager.removeallviews (); Indicatorviewgroup.removeallviews (); }}

Two.

The Viewpager adapter is also very easy

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 very important to control the sliding speed. The very fast effect of self-scrolling default speed is very poor, with Fixedspeedscroller inheriting scroller to achieve 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:o rientation= "Vertical" > <!--drag-and- <android.support.v4.view.viewpager android:id= "@+id/ Marquee_image_viewpager " android:layout_width=" wrap_content " android:layout_height=" 0DP " android: layout_weight= "1" /> <linearlayout android:id= "@+id/marquee_image_bottomviewgroup" Android:layout_width= "Fill_parent" android:layout_height= "wrap_content" android:gravity= "Center_ Horizontal " android:orientation=" Horizontal "> </LinearLayout> </LinearLayout>

Five.

The final step is to change the default animation to achieve a more brilliant effect this part from the network about 10 kinds of animation bar

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

Android Viewpager realizes the marquee switch picture + various toggle animations

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.