How to implement dynamic banner in Android

Source: Internet
Author: User

It can be said that the advertisement is an essential part of the application, there are many applications of the ads in the picture and click on the picture after the logic is fixed, waiting for the next upgrade will change, this mode not only for the user or the application operator experience is relatively poor, of course, the majority of the application of the advertisement is dynamic, so-called dynamic, There are several concepts:

1. The image (address) is returned with the service end;

2. The number of images depends on the number of URLs returned by the server;

3. Click on the image logic to return from the server;

4. Support automatic switching;

Dynamic banner must meet 1.2.3 points, 4th is the additional conditions. So how do we achieve these three points? The first thought is Viewpaper, OK, next we implement a static, if only three pictures:

Look at the layout file first:

<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 "Tools:context =". Mainactivity "> <framelayout android:id=" @+id/fl_ad "android:layout_width=" Fill_parent "Android oid:layout_height= "160dip" > <android.support.v4.view.viewpager android:id= "@+id/vp" an Droid:layout_width= "Fill_parent" android:layout_height= "fill_parent"/> <linearlayout A            Ndroid:layout_width= "Fill_parent" android:layout_height= "30dip" android:layout_gravity= "Bottom" Android:background= "#20000000" android:gravity= "center_vertical" android:orientation= "Vertica L "> <linearlayout android:id=" @+id/ll_dots "android:layout_width=" Wrap_con Tent "Android:layout_height= "Wrap_content" android:layout_gravity= "right" android:layout_marginright= "10DP"                    android:layout_margintop= "3dip" android:gravity= "center" > <view Android:id= "@+id/v_dot0" style= "@style/dot_style" android:background= "@drawable/ic _dot_selected "/> <view android:id=" @+id/v_dot1 "style=" @style/ Dot_style "/> <view android:id=" @+id/v_dot2 "style=" @style/dot_ Style "/> </LinearLayout> </LinearLayout> </FrameLayout></RelativeLayout>


The layout is simple is not, the outer framelayout, then the indicator (white point three) cover the upper part of the viewpaper, adjust the good position.

Look at the main code again:

public class Mainactivity extends Activity {private layoutinflater minflater;private list<view> imageviews;//Slip Dynamic Picture Collection Private View v_dot0,v_dot1,v_dot2;private viewpager vp;private myadapter myadapter; Private list<view> dots; The picture title body of those points private int currentitem = 0; Index number of the current picture private Timer Adtimer = null;//Toggle the currently displayed picture @suppresslint ("Handlerleak") private Handler Handler = new Handler () {p ublic void Handlemessage (Message msg) {switch (msg.what) {case 1:vp.setcurrentitem (CurrentItem);//Toggle the currently displayed picture break;}};}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); minflater = Layoutinflater.from (this); Initview (); Initviewpaper (); adtimer=new Timer (); Adtimer.schedule (New Scrolltask (), 5*1000, 1000);} private void Initview () {vp= (Viewpager) Findviewbyid (R.ID.VP);//White point v_dot0= (View) Findviewbyid (r.id.v_dot0); V_dot1= ( View) Findviewbyid (R.ID.V_DOT1); v_dot2= (view) Findviewbyid (R.ID.V_DOT2);} private void INitviewpaper () {imageviews = new arraylist<view> ();//Initialize picture upper Toggle white point dots=new arraylist<view> ();d Ots.add (v_ DOT0);d Ots.add (v_dot1);d ots.add (V_DOT2);//Initialize picture resource for (int i = 0; I <3; i++) {View view = Minflater.inflate (r.layout.ac TIVITY_PERSONAL_AD_IMG, NULL); ImageView ImageView = (ImageView) View.findviewbyid (r.id.img); switch (i) {case 0: Imageview.setimageresource (R.drawable.ic_launcher);//First picture//Set AD Click event View.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View arg0) {Toast.maketext (Getapplicationcontext (), "clicked 1", Toast.length_long). Show (    ); }}); Break;case 1:imageview.setimageresource (R.drawable.ic_launcher);//second picture//Set AD Click event View.setonclicklistener ( New Onclicklistener () {@Overridepublic void OnClick (View arg0) {Toast.maketext (Getapplicationcontext (), "Clicked 2",    Toast.length_long). Show (); }}); Break;case 2:imageview.setimageresource (R.drawable.ic_launcher);//Third picture//Set AD Click event View.setonclicklistener ( New Onclicklistener () {@Overridepublic void OnClick (View arG0) {Toast.maketext (Getapplicationcontext (), "clicked 3", Toast.length_long). Show (); }}); Imageviews.add (view);} Myadapter= new Myadapter (); Vp.setadapter (myadapter);//Set the adapter to fill the Viewpager page//Set a listener, Call Vp.setonpagechangelistener (new Mypagechangelistener ()) when the page in Viewpager is changed;} /** * Line Shift Task * * @author Byl * */private class Scrolltask extends TimerTask {public void run () {if (imageviews!=null& &imageviews.size () >0) {CurrentItem = (CurrentItem + 1)% imageviews.size (); Handler.sendemptymessage (1);// Toggle picture through Handler}}}/** * call when the state of the page in Viewpager is changed * * @author Byl * */private class Mypagechangelistener implements Onpagech Angelistener {private int oldposition = 0;public void onpageselected (int position) {CurrentItem = Position;dots.get (oldpo sition). Setbackgroundresource (R.drawable.ic_dot_nor);d ots.get (position). Setbackgroundresource (R.drawable.ic_ dot_selected); oldposition = position;} public void onpagescrollstatechanged (int. arg0) {}public void onpagescrolled (int arg0, float arg1, inT arg2) {}}/** * The adapter that fills the Viewpager page * * @author Byl * */private class Myadapter extends Pageradapter {@Overridepublic int GetCount () {return imageviews.size ();} @Overridepublic Object Instantiateitem (View arg0, int arg1) {((Viewpager) arg0). AddView (Imageviews.get (arg1)); return Imageviews.get (arg1);} @Overridepublic void Destroyitem (view arg0, int arg1, Object arg2) {(Viewpager) arg0). Removeview ((view) arg2);} @Overridepublic boolean isviewfromobject (View arg0, Object arg1) {return arg0 = = Arg1;}} @Overrideprotected void OnDestroy () {Super.ondestroy (); if (adtimer!=null) {adtimer.cancel (); adtimer=null;}}

Initviewpaper () adds three ad images (dynamically set) into Imageviews (list<view>) and adds three small white dots to dots in turn(list<view>), set adapter, then Register VP Slide Monitor Vp.setonpagechangelistener (new Mypagechangelistener ()), and change the state of the white point in the onpageselected.

A timer is required for automatic switching:

Adtimer=new Timer (); Adtimer.schedule (new Scrolltask (), 5*1000, 1000);

/** * Line Shift Task *  * @author byl *  */private class Scrolltask extends TimerTask {public void run () {if (Imageviews!=nul L&&imageviews.size () >0) {CurrentItem = (CurrentItem + 1)% imageviews.size (); Handler.sendemptymessage (1); /Toggle picture Through Handler}}}

Toggles the currently displayed picture @suppresslint ("Handlerleak") private Handler Handler = new Handler () {public void Handlemessage (Message msg) { Switch (msg.what) {case 1:vp.setcurrentitem (CurrentItem);//Toggle the currently displayed picture break;}};};
Effect



is not very simple, we know the static banner implementation, then the dynamic advertisement in fact as long as a slight modification can be, nothing more than a few steps:

1. Obtain data returned by the server;

2. Determine the number of imageviews based on the returned data;

3. Determine the click events for each image based on the data returned;

Because the number of ad ads is generally in 3-6, and there is actually no meaning, so I set a maximum of 7 ads, the implementation method is to set the indicator to 7 and all hidden, and then according to the number of images returned by the server to determine the display of several indicators;

First, you extract the attributes of your ad as an object:

1. Image URL;

2. Image click Type; (possibly a web link or an activity in the app)

3. Target link (i.e. the link to jump after clicking)

public class Adv {private string Img_url;private string Type;private string Target_url;public string Getimg_url () {return Img_url;} public void Setimg_url (String img_url) {this.img_url = Img_url;} Public String GetType () {return type;} public void SetType (String type) {this.type = type;} Public String Gettarget_url () {return target_url;} public void Settarget_url (String target_url) {this.target_url = Target_url;}}

Specific properties can be determined according to their own business, the network picture loading I use the afinal open source control, first to simulate the data returned by the server:

private void Initad () {imageresurl=new arraylist<adv> (); ADV adv=new adv (); Adv.setimg_url ("http://media.appshooting.com.tw/wp-content/uploads/2014/03/ 71etnhbdxkl-640x312.jpg "), Adv.settarget_url (" www.baidu.com "), Adv.settype (" 1 "); Imageresurl.add (adv); Adv=new adv ( ); Adv.setimg_url ("http://s.siliconimg.com/kb/content_images/2013/03/25/125164/1364177162_901.jpg"); Adv.settarget_url ("www.baidu.com"), Adv.settype ("1"), Imageresurl.add (ADV), Adv=new adv (), Adv.setimg_url ("http:// Www.ubergizmo.com/wp-content/uploads/2011/02/doubletwist-640x312.jpg "); Adv.settarget_url (" www.baidu.com "); Adv.settype ("1"); Imageresurl.add (adv); adv=new adv (); Adv.setimg_url ("http://cdn.arstechnica.net/wp-content/ Uploads/2013/09/google-plus-services-640x312.jpg "); Adv.settarget_url (" www.baidu.com "); Adv.settype (" 2 "); Imageresurl.add (ADV);}

Initialize Viewpaper:

private void Initviewpaper () {//First white point is all hidden, then v_dot0.setvisibility (View.gone) is displayed based on the number of images obtained; V_dot1.setvisibility ( View.gone); v_dot2.setvisibility (View.gone); v_dot3.setvisibility (View.gone); v_dot4.setvisibility (View.GONE); v_ Dot5.setvisibility (View.gone); v_dot6.setvisibility (view.gone); imageviews = new arraylist<view> ();// Initialize the image upper layer Toggle dot = new arraylist<view> ();//Initialize picture resource for (int i = 0; i < imageresurl.size (); i++) {final ADV Adv=ima Geresurl.get (i); View view = Minflater.inflate (r.layout.activity_personal_ad_img, null); ImageView ImageView = (ImageView) View.findviewbyid (r.id.img); Finalimageloader.display (Imageview,adv.getimg_url ());// Set AD Click event View.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View arg0) {switch ( Integer.parseint (Adv.gettype ())) {Case 1://connection type Intent it = new Intent (Intent.action_view, Uri.parse (adv.gettarget_url ())); It.setclassname ("Com.android.browser", "com.android.browser.BrowserActivity");  StartActivity (IT); Break;case 2:toast.maketexT (Getapplicationcontext (), "clicked", Toast.length_long). Show (); break; }}); Imageviews.add (view); switch (i) {case 0:v_dot0.setvisibility (view.visible);d ots.add (v_dot0); Break;case 1:v_ Dot1.setvisibility (view.visible);d Ots.add (v_dot1), Break;case 2:v_dot2.setvisibility (View.VISIBLE);d Ots.add (v_ DOT2); break;case 3:v_dot3.setvisibility (view.visible);d ots.add (V_DOT3); Break;case 4:v_dot4.setvisibility ( view.visible);d Ots.add (V_DOT4), Break;case 5:v_dot5.setvisibility (view.visible);d ots.add (V_DOT5); Break;case 6:v_ Dot6.setvisibility (view.visible);d ots.add (V_DOT6); if (Imageresurl.size () <=1) {v_dot0.setvisibility (view.gone);} else{for (int i=0;i<dots.size (); i++) {if (i==0) {dots.get (i). Setbackgroundresource (r.drawable.ic_dot_selected);} Else{dots.get (i). Setbackgroundresource (R.drawable.ic_dot_nor);}} Myadapter= new Myadapter (); Vp.setadapter (myadapter);//Set the adapter to fill the Viewpager page//Set a listener, Call Vp.setonpagechangelistener (new Mypagechangelistener ()) when the page in Viewpager is changed;}

In the use of the process found that from the other interface to switch back to the interface, and occasionally appear ad banner white screen phenomenon, so can not be like static ads, always let the advertising picture automatically switch, so I in the Onresume method to start automatic switching, and in the OnPause method stop:

@Overrideprotected void Onresume () {super.onresume (); Currentitem=0;initviewpaper (); adtimer=new Timer (); Adtimer.schedule (New Scrolltask (), 5*1000, 1000);} @Overrideprotected void OnPause () {super.onpause (); if (adtimer!=null) {adtimer.cancel (); adtimer=null;}}

Effect


If you add some animations, you'll be fine:


is not the feeling Bang Bang da!



Source : http://download.csdn.net/detail/baiyuliang2013/8702219

How to implement dynamic banner in Android

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.