Android implements banner interface advertising picture Cycling carousel (including implementing manual sliding Loops) _android

Source: Internet
Author: User
Tags object object

Preface: You will often see that there are some app banner interfaces that allow you to loop through multiple ad images and manually slide loops. This thought that simple viewpager can achieve these functions. But the pain of the egg is coming, Viewpager does not support circular paging. So to realize the loop, you need to do it yourself. I also found some examples on the Internet, the demo of this blog is a combination of some of the relevant examples to find the basis of the transformation, but also want to be useful to readers.

Demo implementation of the effect diagram is as follows:

Demo Code:

The engineering catalogue is as follows:

Nonsense not much to say, on the code.

1. The main activity code is as follows:

Package com.stevenhu.android.phone.ui; 
Import java.util.ArrayList; 
Import java.util.List; 
Import Com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator; 
Import com.nostra13.universalimageloader.core.DisplayImageOptions; 
Import Com.nostra13.universalimageloader.core.ImageLoader; 
Import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; 
Import Com.nostra13.universalimageloader.core.assist.QueueProcessingType; 
Import Com.stevenhu.android.phone.bean.ADInfo; 
Import Com.stevenhu.android.phone.utils.ViewFactory; 
Import Android.annotation.SuppressLint; 
Import android.app.Activity; 
Import Android.os.Bundle; 
Import Android.view.View; 
Import Android.widget.ImageView; 
Import Android.widget.Toast; 
Import Cn.androiddevelop.cycleviewpager.lib.CycleViewPager; 
Import Cn.androiddevelop.cycleviewpager.lib.CycleViewPager.ImageCycleViewListener; /** * Description: Home * * @author Stevenhu * @version May 8, 2015 Morning 10:47:37 * * public class Mainactivity extends ACTIvity {private list<imageview> views = new arraylist<imageview> (); 
Private list<adinfo> infos = new arraylist<adinfo> (); 
Private Cycleviewpager Cycleviewpager; Private string[] Imageurls = {"Http://img.taodiantong.cn/v55183/infoimg/2013-07/130720115322ky.jpg", "http:// Pic30.nipic.com/20130626/8174275_085522448172_2.jpg "," http://pic18.nipic.com/20111215/577405_080531548148_2. JPG "," http://pic15.nipic.com/20110722/2912365_092519919000_2.jpg "," http://pic.58pic.com/58pic/12/64/27/ 
55u58picrdx.jpg "}; 
@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
Setcontentview (R.layout.ui_main); 
Configimageloader (); 
Initialize (); @SuppressLint ("Newapi") private void Initialize () {Cycleviewpager = (Cycleviewpager) Getfragmentmanager (). Findfrag 
Mentbyid (r.id.fragment_cycle_viewpager_content); 
for (int i = 0; i < imageurls.length i + +) {adinfo info = new Adinfo (); 
Info.seturl (Imageurls[i]); Info.setcontenT ("Picture-->" + i); 
Infos.add (info); 
///Add the last ImageView in Views.add (this, Infos.get (Infos.size ()-1). GETURL ()); 
for (int i = 0; i < infos.size (); i++) {Views.add (the Viewfactory.getimageview (this, infos.get (i). GETURL ()); 
///Add the first ImageView in Views.add (this, infos.get (0). GETURL ()); 
Sets the loop to call Cycleviewpager.setcycle (true) before calling the SetData method; 
Set whether to cycle Cycleviewpager.setdata before loading data (views, infos, Madcycleviewlistener); 
Sets the Carousel Cycleviewpager.setwheel (true); 
Set the carousel time, the default 5000ms cycleviewpager.settime (2000); 
Set the dot to indicate the center of the icon group, by default to the right Cycleviewpager.setindicatorcenter (); Private Imagecycleviewlistener Madcycleviewlistener = new Imagecycleviewlistener () {@Override public void onimagecli 
CK (adinfo info, int position, View ImageView) {if (Cycleviewpager.iscycle ()) {position = position-1; 
Toast.maketext (Mainactivity.this, "position-->" + info.getcontent (), Toast.length_short). Show (); 
} 
} 
}; /** * Configuration Imageloder 
* * private void Configimageloader () {//Initialize Imageloader @SuppressWarnings ("deprecation") displayimageoptions options = new Displayimageoptions.builder (). Showstubimage (r.drawable.icon_stub)//Set the picture that is displayed during download of the picture. Showimageforemptyuri ( R.drawable.icon_empty//Set the picture to be displayed when the picture URI is empty or wrong. Showimageonfail (R.drawable.icon_error)//Set picture that appears incorrectly during picture loading or decoding. Cacheinmemory (TRUE)//Set whether the downloaded picture is slow to exist in memory. Cacheondisc (TRUE)//Set whether the downloaded picture is slow to exist in the SD card//. Displayer (New Roundedbitmapdisplayer (20))//set to Fillet picture. Build (); Create a configured displayimageoption Object imageloaderconfiguration config = new Imageloaderconfiguration.builder ( Getapplicationcontext ()). Defaultdisplayimageoptions (Options). ThreadPriority (thread.norm_priority-2). Denycacheimagemultiplesizesinmemory (). Disccachefilenamegenerator (New Md5filenamegenerator ()). 
Tasksprocessingorder (QUEUEPROCESSINGTYPE.LIFO). build (); 
Imageloader.getinstance (). init (config);  } 
}

2. The main file Ui_main.xml code is as follows:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= 
"http://schemas.android.com/apk/" Res/android " 
android:layout_width=" match_parent " 
android:layout_height=" match_parent " 
android:o" rientation= "vertical" > 
<fragment 
android:id= "@+id/fragment_cycle_viewpager_content" 
android: Name= "Cn.androiddevelop.cycleviewpager.lib.CycleViewPager" 
android:layout_width= "Match_parent" 
android:layout_height= "180dip"/> 
<relativelayout 
android:layout_width= "Fill_parent" 
android:layout_height= "0dip" 
android:layout_weight= "1" > 
<textview 
android:layout_width= " Wrap_content " 
android:layout_height=" wrap_content " 
android:layout_centerinparent=" true " 
Android" : text= "Content"/> 
</RelativeLayout> 

The 3.CycleViewPager class code is as follows:

Package cn.androiddevelop.cycleviewpager.lib; 
Import java.util.ArrayList; 
Import java.util.List; 
Import Android.annotation.SuppressLint; 
Import android.app.Fragment; 
Import Android.os.Bundle; 
Import Android.os.Message; 
Import Android.support.v4.view.PagerAdapter; 
Import Android.support.v4.view.ViewPager.OnPageChangeListener; 
Import Android.view.LayoutInflater; 
Import Android.view.View; 
Import Android.view.View.OnClickListener; 
Import Android.view.ViewGroup; 
Import Android.widget.FrameLayout; 
Import Android.widget.ImageView; 
Import Android.widget.LinearLayout; 
Import Android.widget.RelativeLayout; 
Import Com.stevenhu.android.phone.bean.ADInfo; 
Import COM.STEVENHU.ANDROID.PHONE.UI.R; /** * Implementation can be cycled, Viewpager/@SuppressLint ("Newapi") public class Cycleviewpager extends Fragment implements 
Ngelistener {private list<imageview> imageviews = new arraylist<imageview> (); 
Private imageview[] indicators; Private Framelayout ViewpagerfragmentlayoUt Private LinearLayout indicatorlayout; 
Indicator private Baseviewpager Viewpager; 
Private Baseviewpager Parentviewpager; 
Private Viewpageradapter adapter; 
Private Cycleviewpagerhandler handler; private int time = 5000; Default carousel Time private int currentposition = 0; The current position of the carousel is private Boolean isscrolling = false; Whether the scroll box scrolls with private Boolean iscycle = false; Whether the loop private Boolean iswheel = false; Whether the carousel private long releasetime = 0; Finger release, page does not roll time, to prevent mobile phone release after a short time to switch private int WHEEL = 100; Rotate private int wheel_wait = 101; 
Waiting for private imagecycleviewlistener mimagecycleviewlistener; 
Private list<adinfo> infos;  @Override public view Oncreateview (Layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {View view 
= Layoutinflater.from (Getactivity ()). Inflate (r.layout.view_cycle_viewpager_contet, NULL); 
Viewpager = (Baseviewpager) View.findviewbyid (R.id.viewpager); Indicatorlayout = (linearlayout) view. Findviewbyid (R.id.layout_viewpager_indicatoR); 
Viewpagerfragmentlayout = (framelayout) view. Findviewbyid (r.id.layout_viewager_content); Handler = new Cycleviewpagerhandler (getactivity ()) {@Override public void Handlemessage (msg) {Super.handlemes 
Sage (msg); 
if (Msg.what = = WHEEL && imageviews.size ()!= 0) {if (!isscrolling) {int max = imageviews.size () + 1; 
int position = (currentposition + 1)% imageviews.size (); 
Viewpager.setcurrentitem (position, true); 
if (position = max) {//Last page, return to the first page Viewpager.setcurrentitem (1, false); 
} releasetime = System.currenttimemillis (); 
Handler.removecallbacks (runnable); 
Handler.postdelayed (runnable, time); 
Return 
} if (msg.what = = wheel_wait && imageviews.size ()!= 0) {handler.removecallbacks (runnable); 
Handler.postdelayed (runnable, time); 
} 
} 
}; 
return view; } public void SetData (list<imageview> views, list<adinfo> List, Imagecycleviewlistener Listener) {SetData (v) 
Iews, list, listener, 0); }/** * Initialize Viewpager * * @param views * To display the views * @param showposition * Default display position * * public void SetData (list<imageview> views, list<ad 
Info> list, Imagecycleviewlistener listener, int showposition) {Mimagecycleviewlistener = listener; 
Infos = list; 
This.imageViews.clear (); 
if (views.size () = = 0) {viewpagerfragmentlayout.setvisibility (view.gone); 
Return 
for (ImageView item:views) {this.imageViews.add (item); 
int ivsize = Views.size (); 
Set indicator indicators = new Imageview[ivsize]; 
if (iscycle) indicators = new Imageview[ivsize-2]; 
Indicatorlayout.removeallviews (); for (int i = 0; i < indicators.length i++) {View view = Layoutinflater.from (Getactivity ()). Inflate (R.layout.view_c 
Ycle_viewpager_indicator, NULL); 
Indicators[i] = (ImageView) View.findviewbyid (r.id.image_indicator); 
Indicatorlayout.addview (view); 
} adapter = new Viewpageradapter (); 
The default point is to the first item, and the lower viewpager.setcurrentitem will trigger the recalculation indicator pointing to Setindicator (0); 
Viewpager.setoffscreenpagelimit (3); viewpager.seTonpagechangelistener (this); 
Viewpager.setadapter (adapter); 
if (Showposition < 0 | | | showposition >= views.size ()) showposition = 0; 
if (iscycle) {showposition = showposition + 1; 
} viewpager.setcurrentitem (Showposition); /** * Set indicator centered, default indicator on right */public void Setindicatorcenter () {relativelayout.layoutparams params = new relativelayou 
T.layoutparams (RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
Params.addrule (Relativelayout.align_parent_bottom); 
Params.addrule (relativelayout.center_horizontal); 
Indicatorlayout.setlayoutparams (params); /** * Whether the loop, default does not open, before opening, please add the front and the last face of the views to each of the view, for the loop * * @param iscycle * Whether the cycle/public void Setcycle (Boolean iscycl 
E) {this.iscycle = iscycle; 
/** * is in a circular state * * @return/public boolean iscycle () {return iscycle;  
/** * Set whether the carousel, the default does not carousel, the carousel must be the cycle of * * @param iswheel/public void Setwheel (Boolean iswheel) {this.iswheel = Iswheel; 
Iscycle = true; if (Iswheel) {
Handler.postdelayed (runnable, time); 
}/** * is in a carousel state * * @return/public boolean iswheel () {return iswheel; Final Runnable Runnable = new Runnable () {@Override public void run () {if (getactivity ()!= null &&!GETAC 
Tivity (). isfinishing () && Iswheel) {Long now = System.currenttimemillis (); 
Detects if there is a strike (hand sliding) operation between the previous slide time and the current one, and some words await the next carousel if (Now-releasetime > time-500) {handler.sendemptymessage (WHEEL); 
else {handler.sendemptymessage (wheel_wait); 
} 
} 
} 
}; /** * Releases the indicator height, possibly because the previous indicator has been limited to the height, here free/public void Releaseheight () {GetView (). Getlayoutparams (). Height = relativelayou 
T.layoutparams.match_parent; 
RefreshData (); /** * Set the Carousel pause time, that is, not many seconds to switch to the next view. Default 5000ms * * @param time * milliseconds/public void settime (int time) {this.time = Tim 
E 
/** * Refreshes the data and notifies the refresh data after the external view is updated/public void RefreshData () {if (adapter!= null) adapter.notifydatasetchanged (); }/** * Hide Cycleviewpager */public void Hide () {ViewpagerfragmentlaYout.setvisibility (View.gone); 
/** * Returns the built-in Viewpager * * @return Viewpager/public Baseviewpager Getviewpager () {return viewpager; /** * Page Adapter returns the corresponding view * * @author yuedong Li */Private class Viewpageradapter extends Pageradapter {@Overrid 
e public int GetCount () {return imageviews.size (); 
@Override public boolean isviewfromobject (View arg0, Object arg1) {return arg0 = = Arg1; @Override public void Destroyitem (ViewGroup container, int position, object object) {Container.removeview (View) obj 
ECT); @Override public View Instantiateitem (ViewGroup container, final int position) {ImageView v = imageviews.get (positio 
n); if (Mimagecycleviewlistener!= null) {V.setonclicklistener (new Onclicklistener () {@Override public void OnClick (View 
V) {Mimagecycleviewlistener.onimageclick (Infos.get (currentPosition-1), currentposition, V); 
} 
}); 
} container.addview (v); 
return v; @Override public int GetItemPosition (Object object) {Return Position_none; 
@Override public void onpagescrollstatechanged (int arg0) {if (arg0 = 1) {//Viewpager in scrolling isscrolling = true; 
Return 
else if (arg0 = = 0) {//Viewpager scrolling End if (parentviewpager!= null) parentviewpager.setscrollable (TRUE); 
Releasetime = System.currenttimemillis (); 
Viewpager.setcurrentitem (currentposition, false); 
} isscrolling = false; @Override public void onpagescrolled (int arg0, float arg1, int arg2) {} @Override public void onpageselected (int a 
RG0) {int max = Imageviews.size ()-1; 
int position = arg0; 
CurrentPosition = arg0; 
if (iscycle) {if (arg0 = = 0) {currentposition = max-1; 
else if (arg0 = max) {currentposition = 1; 
} position = currentPosition-1; 
} setindicator (position); /** * Sets whether Viewpager can be scrolled * * @param enable/public void Setscrollable (Boolean enable) {viewpager.setscrollable ( 
Enable); /** * Returns the current position, the loop needs to be aware that the returned position contains the view that was previously added to the front and last side of the views, that is, where the current page is attempting to be in the points collection * * @return/Public INT Getcurrentpostion () {return currentposition; /** * Set Indicator * * @param selectedposition * Default indicator position * * private void Setindicator (int selectedposition) {for (int i = 0; i < indicators.length; 
i++) {indicators[i]. Setbackgroundresource (R.drawable.icon_point); } if (Indicators.length > Selectedposition) indicators[selectedposition]. Setbackgroundresource (R.drawable.icon_ 
POINT_PRE); /** * If the current page is nested in another viewpager, in order to block the parent Viewpager scrolling while scrolling, you can prevent the parent Viewpager from sliding events * The parent Viewpager needs to implement the Setscrollable method in Parentviewpager/public void disableparentviewpagertouchevent (Baseviewpager 
Parentviewpager) {if (Parentviewpager!= null) parentviewpager.setscrollable (FALSE); /** * Monitor event for Carousel control * * @author minking/public static interface Imagecycleviewlistener {/** * click picture Event * * @para 
M position * @param imageview */public void Onimageclick (adinfo info, int postion, View imageview); } 
}

Cycleviewpager class for the implementation of recyclable, Viewpager core class, inherited from the fragment, the implementation of the principle is not much said, the code has relevant comments.

The above is a small set of Android to introduce the implementation of the banner interface advertising picture Cycle Carousel (including the implementation of manual sliding cycle), I hope to help!

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.