Ad banner: Manual swipe switch, auto switch, click Jump, asynchronous Load network picture

Source: Internet
Author: User
Tags addall

:

The banner function has automatic switch picture, click the picture can customize the event, manually swipe to switch, load the picture asynchronously

Code to speak:

Layout file:

<!--ad--<framelayout android:id= "@+id/new_recommend"                Android:layout_width= "Fill_parent" android:layout_height= "Wrap_content" > <com.cyou.cmall.ui.horizontalviewpager android:id= "@+id/viewpager" android:layou                    T_width= "Fill_parent" android:layout_height= "fill_parent"/> <linearlayout Android:id= "@+id/ll_indicator" android:layout_width= "Wrap_content" Andro id:layout_height= "Wrap_content" android:layout_gravity= "Bottom" android:orientation=            "Horizontal" android:paddingbottom= "8DP" android:paddingleft= "26dip"/> </framelayout> 


In the layout file I have customized a horizontalviewpager, which is based on the Viewpager to make some changes, the reason is because the project is used in the drop-down refresh control, the layout of the outermost layer has a scrollview, Causes ScrollView to intercept gesture events, while Viewpager does not get a swipe gesture

Here is the code for Horizontalviewpager, if you do not need to handle the swipe gesture, you can use the system's Viewpager control completely

/** * Replication This control is because in Pulltorefreshscrollview, Viewpager cannot swipe horizontally * * @author Wangwei_cs */public class Horizontalviewpager    Extends Viewpager {private Gesturedetector mgesturedetector;        Public Horizontalviewpager (context context, AttributeSet Attrs) {Super (context, attrs);    Init (context);        } public Horizontalviewpager (context context) {super (context);    Init (context);    } private void Init (context context) {Mgesturedetector = new Gesturedetector (context, new Yscrolldetector ()); } @Override public boolean dispatchtouchevent (Motionevent ev) {Boolean dispatchtouchevent = Super.dispatch        TouchEvent (EV);                if (dispatchtouchevent) {if (mgesturedetector.ontouchevent (EV)) {//Request parent class Abort event handling            Requestdisallowintercepttouchevent (TRUE);    }} return dispatchtouchevent; } class Yscrolldetector extends Simpleongesturelistener {@Override public boolean onscroll(Motionevent E1, motionevent E2, float Distancex, float distancey)        {//If we scroll closer to the horizontal direction, return true, handle it ourselves, otherwise, let go of the processing permission return (Math.Abs (Distancex) > Math.Abs (Distancey)); }}}</span>


What to do: Call the method in the program OnCreate method

    /** * Initialize recommended AD zone */private void Initrecommendad () {Horizontalviewpager Mviewpager = (horizontalview        Pager) Findviewbyid (R.id.viewpager);        Mindicatorlayout = (linearlayout) Findviewbyid (r.id.ll_indicator); Framelayout.layoutparams params = new Framelayout.layoutparams (Android.widget.FrameLayout.LayoutParams.MAT        ch_parent, Height * 24/100);        Mviewpager.setlayoutparams (params);            Adimagepageradapter mpageradapter = new Adimagepageradapter (MCXT, Imageurls, New Viewpageritemclicklistener () {                    @Override public void Onviewpageritemclick (int position) {if (imageurls.size () > 0) {                        if (imageurls.size () = = 1) {Boolean enable = Urlenable (Imageurls.get (0));                        if (enable) {handleclickevent (position);      }} else {handleclickevent (position);              }                }            }        });        list<string> lastadurls = Getlastadurls (); if (Lastadurls = = NULL | | lastadurls.size () = = 0) {//No previous ad URL information was recorded, add an invalid URL path Imageurls.add (Cons Tants.            Invalid_url);        LOGHELPER.E (TAG, "No last ad record");            } else {LOGHELPER.E (TAG, "show last ad record");        Imageurls.addall (Lastadurls); } madcomponent = new Recommendadcomponent (MCXT, Mviewpager, Mpageradapter, Imageurls, Mindicat        Orlayout);        Madcomponent.startupadcomponent ();    Mpageradapter.notifydatasetchanged (); }


Below is the source code of Adimagepageradapter

Import Java.util.list;import Android.content.context;import Android.graphics.bitmap;import Android.support.v4.view.pageradapter;import Android.view.layoutinflater;import Android.view.View;import Android.view.view.onclicklistener;import Android.view.viewgroup;import Android.widget.adapterview;import Android.widget.adapterview.onitemclicklistener;import Android.widget.imageview;import Android.widget.ProgressBar ; Import Android.widget.toast;import Com.nostra13.universalimageloader.core.displayimageoptions;import Com.nostra13.universalimageloader.core.imageloader;import Com.nostra13.universalimageloader.core.assist.failreason;import Com.nostra13.universalimageloader.core.assist.imagescaletype;import Com.nostra13.universalimageloader.core.assist.simpleimageloadinglistener;import com.nostra13.universalimageloader.core.display.fadeinbitmapdisplayer;/** * Infinite Loop Adapter * * @author Wangwei_cs */ public class Adimagepageradapter extends Pageradapter {protected static final String TAG = "AdimagePageradapter ";    Private list<string> Imageurls;    Private Layoutinflater Inflater;    Private Context mcxt;    Private Viewpageritemclicklistener Mlistener;    protected Imageloader Imageloader;    Private displayimageoptions options; Public Adimagepageradapter (context context, list<string> Imageurls, Viewpageritemclicklistener listener) {th        Is.imageurls = Imageurls;        THIS.MCXT = context;        Inflater = Layoutinflater.from (context);        This.mlistener = listener;        Imageloader = Imageloader.getinstance (); options = new Displayimageoptions.builder (). Showimageforemptyuri (r.drawable.ad_default). sh Owimageonfail (R.drawable.ad_default). showimageonloading (R.drawable.ad_default). Resetviewbe                Foreloading (True). Cacheondisc (True). Imagescaletype (imagescaletype.exactly) . Bitmapconfig (Bitmap.Config.RGB_565). Considerexifparams (trUE). Displayer (new Fadeinbitmapdisplayer). Build ();        } @Override public int getcount () {if (Imageurls.size () < 2) {return imageurls.size ();    } return integer.max_value;    } @Override public boolean isviewfromobject (View arg0, Object arg1) {return arg0 = = Arg1; } @Override Public Object instantiateitem (viewgroup container, int position) {Final int index = position% i        Mageurls.size ();        View view = Inflater.inflate (R.layout.item_pager_image, container, false);        Assert view! = NULL;        ImageView ImageView = (ImageView) View.findviewbyid (r.id.image);        Final ProgressBar spinner = (ProgressBar) View.findviewbyid (r.id.img_loading);                    Imageloader.displayimage (Imageurls.get (index), ImageView, Options, new Simpleimageloadinglistener () {     @Override public void onloadingstarted (String imageuri, view view) {                   Spinner.setvisibility (view.visible); } @Override public void onloadingfailed (String imageuri, view view, Failreason FAILR                        Eason) {String message = NULL; Switch (Failreason.gettype ()) {Case io_error:message = "input/                                Output error ";                            Break                                Case decoding_error:message = "Image can ' t is decoded";                            Break                                Case network_denied:message = "Downloads is DENIED";                            Break                                Case out_of_memory:message = "Out of MEMORY error";                            Break Case unknown:message = "UNKNOWN error";                        Break                        } LOGHELPER.E (TAG, message);                    Spinner.setvisibility (View.gone); } @Override public void Onloadingcomplete (String imageuri, view view, Bitmap Loadedi                    Mage) {spinner.setvisibility (view.gone);        }                });                View.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {                if (Mlistener!=null) {Mlistener.onviewpageritemclick (index);        }            }        });        Container.addview (view);    return view; } @Override public void Destroyitem (ViewGroup container, int position, object object) {Container.removeview (    (View) object); }}

Here are the highlights of the Recommendadcomponent custom AD recommendation component

Import Android.annotation.suppresslint;import Android.content.context;import Android.os.handler;import Android.support.v4.view.pageradapter;import Android.support.v4.view.viewpager;import Android.support.v4.view.viewpager.onpagechangelistener;import Android.support.v4.view.ViewPager.PageTransformer ; Import Android.view.view;import Android.view.viewgroup.layoutparams;import android.view.animation.AnimationUtils ; Import Android.widget.imageview;import android.widget.linearlayout;import java.util.list;import Java.util.Timer; Import java.util.timertask;/** * Display AD rotation components * * @author Wangwei_cs */public class Recommendadcomponent {/** * Invalid diagram    Slice switching time, if 0 means not automatically switching */public static final int switch_time_invalid = 0;    Private Context mcxt;    Picture URL collection private list<string> mimgurls;    Picture switch time private int mswitchtime;    Auto-scrolling timer private timer Mtimer;    Show the layout of the dot indicator private linearlayout mindicatorlayout;    Private Viewpager Mviewpager; Private Pageradapter Mpageradapter; private int currentindex; The current page, in 0 and GetSize () direct private int pagercurrent;//in Viewpager, the current page, takes value between 0 and Integer.max_value private boolean Timerun    Ning  /** * @param context * @param viewpager viewpager Component * @param pageradapter * @param adurls A collection of picture URLs installed * @param switchtime Picture Switch Time (ms) {@link Recommendadcomponent#switch_time_invalid}: Do not switch automatically * @param indicatorlayout display the dot indicator Layout */Public recommendadcomponent (context context, Viewpager Viewpager, Pageradapter pageradapter, LIST&LT;STRING&G T        Adurls, int switchtime, LinearLayout indicatorlayout) {this.mcxt = context;        This.mviewpager = Viewpager;        This.mpageradapter = Pageradapter;        This.mimgurls = Adurls;        This.mswitchtime = Switchtime;        This.mindicatorlayout = Indicatorlayout;        Initindicatorlayout ();    Mviewpager.setonpagechangelistener (New Myonpagechangelistener ());//Setviewpageranimator ();     }/** * Initialization indicator*/private void Initindicatorlayout () {ImageView IV = NULL; if (mindicatorlayout! = null && getsize () < 2) {//If the dot container is not shown when there is only one figure Mindicatorlayout.setv        Isibility (view.invisible);            } else if (mindicatorlayout! = null) {mindicatorlayout.setvisibility (view.visible);                for (int i = 0; i < getsize (); i++) {IV = new ImageView (MCXT);                Iv.settag (i);                int padding = mcxt.getresources (). Getdimensionpixelsize (r.dimen.indicator_padding); Linearlayout.layoutparams params = new Linearlayout.layoutparams (layoutparams.wrap_content, LayoutP Arams.                Wrap_content);                Params.setmargins (padding, 0, padding, 0);            Mindicatorlayout.addview (iv, params);        }}} private void Resetindicatorlayout () {mindicatorlayout.removeallviews ();    Initindicatorlayout (); }/** * Animate Viewpager */   private void Setviewpageranimator () {if (Mviewpager!=null) {Pagetransformer pagetransformer=new Pag Etransformer () {@Override public void transformpage (view view, float arg1) {//View.setanimation (Animationutils.loadanimation (MCXT, Android).                    R.anim.slide_out_right));                View.setanimation (Animationutils.loadanimation (MCXT, r.anim.right_in));            }            };        Mviewpager.setpagetransformer (True, Pagetransformer);  }}/** * Gets the size of the collection of pictures * * @return */private int getsize () {return (Mimgurls = = null? 0    : Mimgurls.size ());    } public boolean IsEmpty () {return (Mimgurls = = null);        }/** * Open components */public void startupadcomponent () {currentindex = 0;        pagercurrent = 0;        Mviewpager.setadapter (Mpageradapter);        Mviewpager.setcurrentitem (Currentindex); Updateindicator (CurrenTindex);    Starttimer ();        }/** * Update adapter data in component */public void updateadcomponent () {Stoptimer ();        Resetindicatorlayout ();        Mpageradapter.notifydatasetchanged ();    Startupadcomponent ();    /** * Call this method when the page is destroyed */public void stopadcomponent () {Stoptimer ();        }/** * Stop auto-scrolling task */public void Stoptimer () {timerunning = false;            if (Mtimer! = null) {Mtimer.cancel ();        Mtimer = null;        }}/** * Start the task of automatic scrolling, note that only the number of pictures greater than 1 will automatically scroll */public void Starttimer () {timerunning = true;            if (Mtimer = = null && getsize () > 1 && mswitchtime > 0) {mtimer = new Timer ();        Mtimer.schedule (New Pagertimertask (), Mswitchtime, mswitchtime); }} Private class Pagertimertask extends TimerTask {@Override public void run () {Currenti            ndex++;            pagercurrent++; MhandLer.sendemptymessage (0); }} Private class Myonpagechangelistener implements Onpagechangelistener {@Override public void Onpag escrollstatechanged (int arg0) {} @Override public void onpagescrolled (int arg0, float arg1, int arg2            {} @Override public void onpageselected (int position) {pagercurrent = position;        Currentindex = position% getsize ();//Update current page updateindicator (currentindex); }}/** * Update the DOT indicator */private void updateindicator (int position) {if (!isempty () && Positi                On < GetSize ()) {if (GetSize () > 1) {resetallindicator (GetSize ());//Reset All indicators to select State                View v = mindicatorlayout.findviewwithtag (position);            if (v! = null) {V.setbackgroundresource (r.drawable.circle_indicator_selected);//lit}   }}}/** * Reset All indicators */ private void Resetallindicator (int size) {if (mindicatorlayout! = null) {for (int i = 0; i < size;                i++) {View v = mindicatorlayout.findviewwithtag (i);                if (v! = null) {V.setbackgroundresource (r.drawable.circle_indicator_normal); }}}} @SuppressLint ("Handlerleak") private Handler Mhandler = new Handler () {Publ        IC void Handlemessage (Android.os.Message msg) {Mviewpager.setcurrentitem (pagercurrent);    }; };}

When the network loads the image URL list successfully, just call Madcomponent.updateadcomponent ();

For example, my Code

private void Updateadsources (list

Ad banner: Manual swipe switch, auto switch, click Jump, asynchronous Load network picture

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.