Viewpager (on) -- Automatic ad carousel

Source: Internet
Author: User

In this example, viewpager is used to implement automatic ad carousel and the function of displaying and clicking on small dots is a more practical function.

In this example, the playback, sliding, and position can be adjusted at will, which is more flexible. In the original project, three levels of cache are added, however, if I want to write a cache, I will first take the image for a demo.

If you have any good suggestions, please come up and make progress together ..

:



Code structure: mainly contains three files, the main class, viewpager adapter, and XML layout of the page

There are many principles on the Internet, so I won't say much about writing more detailed comments directly on the code --

Main class

<Span style = "font-size: 14px;"> package COM. example. viewpagerimage; import Java. util. arraylist; import Java. util. timer; import Java. util. timertask; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. support. v4.view. viewpager; import android. support. v4.view. viewpager. onpagechangelistener; import android. view. view; import android. view. viewgroup; import android. widget. imageview; import android. widget. linearlayout; import android. widget. relativelayout; import android. annotation. suppresslint; import android. app. activity; public class mainactivity extends activity {/* store carousel images */Public int [] mybanner = {R. drawable. banner3, R. drawable. banner2, R. drawable. banner1};/* carousel container viewpager */Public viewpager mviewpager;/* viewpager adapter */Public viewpageradapter mviewpageradapter;/* store image resources */Public arraylist <imageview> mimagelist; /* store advertisement carousel bullets */Public imageview ivdicator [];/* carousel bullets */public view vdicator;/* layout parameter */Public linearlayout. layoutparams mlayoutparams;/* timer */Public timer mtimer; Public timertask mtimertask; Public int mtimernum = 0; public final int picture = 0x1; @ suppresslint ("handlerleak ") handler mhandler = new handler () {@ overridepublic void handlemessage (Message MSG) {Switch (MSG. what) {Case picture: setmypagerindex (); break;} super. handlemessage (MSG) ;}}; @ override protected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); // obtain the value of 2 @ suppresswarnings ("deprecation") int screenheight = This. getwindowmanager (). getdefadisplay display (). getheight ()/5*2; // set the location of viewpager relativelayout layout = (relativelayout) This. findviewbyid (R. id. id_main_layout0); relativelayout. layoutparams Params = (relativelayout. layoutparams) layout. getlayoutparams (); Params. height = screenheight; layout. setlayoutparams (Params); Init () ;}/ *** initialize the component **/Public void Init () {mimagelist = new arraylist <imageview> (); ivdicator = new imageview [mybanner. length]; mlayoutparams = new linearlayout. layoutparams (10, 10); // set the distance between the border of a small dot and the mlayoutparams. setmargins (7, 10, 7, 10); // small dot object vdicator = This. findviewbyid (R. id. viewpager_indicator); // you can specify the number of carousel images and small dots for (INT I = 0; I <mybanner. length; I ++) {imageview nowimageview = new imageview (this); nowimageview. setimageresource (mybanner [I]); mimagelist. add (nowimageview); nowimageview = new imageview (this); nowimageview. setlayoutparams (mlayoutparams); nowimageview. setbackgroundresource (R. drawable. indicator); ivdicator [I] = nowimageview; // Add a small dot (viewgroup) vdicator) one by one ). addview (ivdicator [I]);} mviewpager = (viewpager) This. findviewbyid (R. id. viewpager); mviewpageradapter = new viewpageradapter (mimagelist, this); // Add the adapter mviewpager to viewpager. setadapter (mviewpageradapter); // Add a sliding listener mviewpager to viewpager. setonpagechangelistener (New onpagechangelistener () {@ overridepublic void onpagescrollstatechanged (INT arg0) {}@ overridepublic void onpagescrolled (INT arg0, float arg1, int arg2) {}@ overridepublic void onpageselected (INT arg0) {setdicator (arg0) ;}); // setdicator (0); starttimer ();} /*** Enable Automatic ad carousel **/Public void starttimer () {mtimer = new timer (); mtimertask = new timertask () {@ overridepublic void run () {mtimernum ++; // call mhandler asynchronously. sendemptymessage (picture) ;}}; // you can call mtimer once every 4 seconds. schedule (mtimertask, 4*1000, 4*1000);}/*** switch ad animation **/Public void setmypagerindex () {try {If (mtimernum> = mybanner. length) {mtimernum = 0;} mviewpager. setcurrentitem (mtimernum, true);} catch (exception e) {e. printstacktrace () ;}}/*** set the background of a small dot **/Public void setdicator (Int J) {// set the number of carousel charts and small dots for (INT I = 0; I <mybanner. length; I ++) {if (I = J) {ivdicator [I]. setbackgroundresource (R. drawable. indicator_focused);} else {ivdicator [I]. setbackgroundresource (R. drawable. indicator) ;}}/ ** stop scheduled task **/Public void stoptask () {try {mtimer. cancel ();} catch (exception e) {e. printstacktrace () ;}}</span>


Viewpager Adapter

<Span style = "font-size: 14px;"> package COM. example. viewpagerimage; import Java. util. arraylist; import android. app. activity; import android. support. v4.view. pageradapter; import android. view. view; import android. view. view. onclicklistener; import android. view. viewgroup; import android. widget. imageview; public class viewpageradapter extends pageradapter {public arraylist <imageview> mimageview; public activity mactivity; Public viewpageradapter (arraylist <imageview> mimageview, activity mactivity) {This. mimageview = mimageview; this. mactivity = mactivity;} @ overridepublic int getcount () {return mimageview. size ();}/*** determine whether the two images are consistent */@ overridepublic Boolean isviewfromobject (view arg0, object arg1) {return arg0 = arg1 ;} /*** return the image to be displayed to the adapter **/@ overridepublic object instantiateitem (viewgroup container, int position) {container. addview (mimageview. get (position); // view mview = mimageview of the AD carousel image click action. get (position); mview. setonclicklistener (New onclicklistener () {@overridepublic void onclick (view arg0) {;}}); Return mimageview. get (position);}/*** remove the current view from viewgroup **/@ overridepublic void destroyitem (viewgroup container, int position, object) {container. removeview (mimageview. get (position) ;}}</span>

The only XML file in this example

<span style="font-size:14px;"><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="#000"    tools:context=".MainActivity" >    <RelativeLayout        android:id="@+id/id_main_layout0"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginLeft="4dip"        android:layout_marginRight="4dip" >        <android.support.v4.view.ViewPager            android:id="@+id/viewpager"            android:layout_width="match_parent"            android:layout_height="wrap_content" />        <LinearLayout            android:id="@+id/viewpager_indicator"            android:layout_width="100dip"            android:layout_height="20dip"            android:layout_alignBottom="@id/viewpager"            android:layout_alignParentRight="true"            android:layout_marginBottom="12dip"            android:orientation="horizontal" >        </LinearLayout>    </RelativeLayout></RelativeLayout></span>



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.