Android UI implements AD banner Carousel effect _android

Source: Internet
Author: User
Tags getdate visibility

This blog to share an effect is to achieve the advertising banner carousel effect, this effect is also more common, some video class applications are often, take 360 film encyclopedia to give examples:

The effect of living with the red box is the wizard to share today, first to think about what control will be used? What is the user experience?

Control we may be able to think of the nature is Viewpager, yes! What is the user experience of using Viewpager, it may have the following experiences:

1. Switch the picture continuously, the indicator also follows the change

2. Click on the picture to jump to the specified page

How to achieve it?

Layout set to begin
/bannerautoscrolldemo/res/layout/banner.xml

<?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:orientation=" vertical " > <framelayout android:layout_width= "match_parent" android:layout_height= "210DP" > &LT;ANDROID.SUPPORT.V 4.view. Viewpager android:id= "@+id/vp" android:layout_width= "match_parent" android:layout_height= "210DP"/> <Rel Ativelayout android:layout_width= "match_parent" android:layout_height= wrap_content "android:layout_gravity=" Bott Om "android:background=" @drawable/shadow_article "> <textview android:id=" @+id/tv_date "android:layou T_width= "Wrap_content" android:layout_height= "wrap_content" android:layout_above= "@+id/author_layout" Android: Layout_marginbottom= "10DP" android:layout_marginleft= "10DP" android:maxlines= "2" android:text= "March 4" Andro
    Id:textcolor= "@color/white"Android:textsize= "18sp"/> <textview android:id= "@+id/tv_title" android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:layout_above= "@+id/author_layout" android:layout_marginbottom= "10DP
    "Android:layout_marginleft=" 10DP "android:layout_marginright=" 10DP "android:layout_torightof=" @+id/tv_date " Android:maxlines= "2" android:text= "I'm just having the same namesake" android:textcolor= "@color/white" android:textsize= "18SP"/&gt

   ; <relativelayout android:id= "@+id/author_layout" android:layout_width= "Match_parent" Wrap_content "android:layout_alignparentbottom=" true "android:layout_marginleft=" 10DP "android:gravity=" center _vertical "android:paddingbottom=" 20DP "> <textview android:id=" @+id/tv_pre "android:layout_width 
     = "Wrap_content" android:layout_height= "wrap_content" android:text= "article selected from" android:textcolor= "@color/white" Android:textsiZe= "12SP"/> <textview android:id= "@+id/tv_topic_from" android:layout_width= "Wrap_content" Andro id:layout_height= "Wrap_content" android:layout_torightof= "@+id/tv_pre" android:text= "an otaku" android:textColor = "@color/white" android:textsize= "12sp"/> <textview android:id= "@+id/tv_topic" Android:layout_w Idth= "Wrap_content" android:layout_height= "wrap_content" android:layout_marginleft= "10DP" android:layout_to rightof= "@+id/tv_topic_from" android:text= "I want to know what is the relationship between the Fox-Ann and the plan?" "" "Android:textcolor=" @color/white "android:textsize=" 12sp "/> </RelativeLayout> </relativelayo ut> <linearlayout android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:layou t_margintop= "10dip" android:layout_gravity= "Bottom|center_horizontal" android:layout_marginbottom= "10DP" Android: gravity= "center" > <view android:id= "@+id/v_dot0" style= "@stylE/dot_style "android:background=" @drawable/dot_focused "android:visibility=" invisible "/> <View Andr Oid:id= "@+id/v_dot1" style= "@style/dot_style" android:visibility= "invisible"/> The <view android:id= "@+ 
    Id/v_dot2 "style=" @style/dot_style "android:visibility=" invisible "/> <view android:id=" @+id/v_dot3 " style= "@style/dot_style" android:visibility= "invisible"/> <view android:id= "@+id/v_dot4" style = "@style/dot_style" android:visibility= "invisible"/> </LinearLayout> </FrameLayout> </linearlay

 Out>

A Viewpager, the following five points, note that each point has the same style, we define the style in Style.xml:
/bannerautoscrolldemo/res/values/styles.xml

<style name= "Dot_style" >
  <item name= "android:layout_width" >5dip</item>
  <item name= " Android:layout_height ">5dip</item>
  <item name=" Android:background "> @drawable/dot_normal</ item>
  <item name= "Android:layout_marginleft" >1.5dip</item>
  <item name= "Android:layout_ MarginRight ">1.5dip</item>
 </style>

To define a dot graphic resource
/bannerautoscrolldemo/res/drawable/dot_normal.xml

<?xml version= "1.0" encoding= "Utf-8"?> <shape xmlns:android=
"http://schemas.android.com/apk/res/" Android "
 android:shape=" Oval >

 <solid android:color= "#33000000"/>

 <corners android: radius= "5dip"/>

</shape>

/bannerautoscrolldemo/res/drawable/dot_focused.xml

<?xml version= "1.0" encoding= "Utf-8"?> <shape xmlns:android=
"http://schemas.android.com/apk/res/" Android "
 android:shape=" Oval >

 <solid android:color= "#aaFFFFFF"/>

 <corners android: radius= "5dip"/>

</shape>

Define an ad entity
/bannerautoscrolldemo/src/com/xiaowu/banner/demo/addomain.java

Package Com.xiaowu.banner.demo; 
 /** * * @author wwj_748 * * */public class ADDomain {private string id;//AD ID private string date;//Date Private String title; Title Private String Topicfrom; Topics from private String topic; Topics private String imgurl; Picture URL Private Boolean isAd; Is the advertisement private String starttime; Ad start time private String endtime; Ad End Time private String targeturl; Target URL private int width; wide private int height; High private Boolean available;
 Whether public String GetId () {return ID is available;
 public void SetId (String id) {this.id = ID;
 Public String GetTitle () {return title;
 public void Settitle (String title) {this.title = title;
 Public String Getimgurl () {return imgurl;
 } public void Setimgurl (String imgurl) {this.imgurl = Imgurl;
 public Boolean isAd () {return isAd;
 } public void Setad (Boolean isAd) {This.isad = IsAd;
 Public String GetDate () {return date; } public void Setdate (StRing Date {this.date = date;
 Public String Gettopic () {return topic;
 } public void Settopic (String topic) {this.topic = topic;
 Public String Gettopicfrom () {return topicfrom;
 } public void Settopicfrom (String topicfrom) {this.topicfrom = Topicfrom;
 Public String GetStartTime () {return starttime;
 } public void Setstarttime (String starttime) {this.starttime = StartTime;
 Public String Getendtime () {return endtime;
 } public void Setendtime (String endtime) {this.endtime = Endtime;
 Public String Gettargeturl () {return targeturl;
 } public void Settargeturl (String targeturl) {this.targeturl = TargetUrl;
 public int getwidth () {return width;
 public void setwidth (int width) {this.width = width;
 public int getheight () {return height;
 public void setheight (int height) {this.height = height;
 public boolean isavailable () {return available; } public void Setavailable (Boolean available) {THIS.AVAILABLe = available;

 }
 

}

Implementing switching logic

1. Timing switch

2. Switch pictures

3. Toggle Title

4. Toggle Indicator

A timer switch uses a class: Scheduledexecutorservice

The role is timed to perform tasks, we have to do the timing of the task is, 2 seconds to perform a picture switch

private void Startad () {
 scheduledexecutorservice = Executors.newsinglethreadscheduledexecutor ();
 When the activity is displayed, switch every two seconds to the picture display
 scheduledexecutorservice.scheduleatfixedrate (new Scrolltask (), 1, 2,
 timeunit.seconds);
 }

Defining Child Threads

Private class Scrolltask implements Runnable {

 @Override public
 void Run () {
 synchronized (Adviewpager) { C12/>currentitem = (currentitem + 1)% imageviews.size ();
 Handler.obtainmessage (). Sendtotarget ();
 

To notify Viewpager of view switching through handle

Private Handler Handler = new Handler () {public
 void Handlemessage (Android.os.Message msg) {
 Adviewpager.setcurrentitem (CurrentItem);
 };
 

We provide analog data to test

/** * Carousel Broadcast Analog Data * * @return/public static list<addomain> Getbannerad () {list<addomain> adlist = new

 Arraylist<addomain> ();
 ADDomain addomain = new ADDomain ();
 Addomain.setid ("108078");
 Addomain.setdate ("March 4");
 Addomain.settitle ("I have only the same surname as the order Plan");
 Addomain.settopicfrom ("a curtilage"); Addomain.settopic ("I want to know what's the relationship between the Fox and the plan?"
 ");
 Addomain.setimgurl ("/d50735fae6cd7b8900d74cd40c2442a7d9330e29.jpg");
 Addomain.setad (FALSE);

 Adlist.add (ADDomain);
 ADDomain adDomain2 = new ADDomain ();
 Addomain2.setid ("108078");
 Addomain2.setdate ("March 5");
 Addomain2.settitle ("I have only the same surname as the order Plan");
 Addomain2.settopicfrom ("Little Witch"); Addomain2.settopic ("I want to know what is the relationship between the Fox and the plan?"
 ”");
 AdDomain2. Setimgurl ("/eaf81a4c510fd9f9a1edb58b262dd42a2934a45e.jpg");
 Addomain2.setad (FALSE);

 Adlist.add (adDomain2);
 ADDomain adDomain3 = new ADDomain ();
 Addomain3.setid ("108078");
 Addomain3.setdate ("March 6");
 Addomain3.settitle ("I have only the same surname as the order Plan");
 Addomain3.settopicfrom ("Xu Dong"); Addomain3.settopic ("I want to know what is the relationship between the Fox and the plan?"
 ”"); AdDoMain3. Setimgurl ("/8718367adab44aed22a58aeeb11c8701a08bfbd4.jpg");
 Addomain3.setad (FALSE);

 Adlist.add (adDomain3);
 ADDomain adDomain4 = new ADDomain ();
 Addomain4.setid ("108078");
 Addomain4.setdate ("March 7");
 Addomain4.settitle ("I have only the same surname as the order Plan");
 Addomain4.settopicfrom ("small soft"); Addomain4.settopic ("I want to know what is the relationship between the Fox and the plan?"
 ”");
 AdDomain4. Setimgurl ("/a686c9177f3e670932e4cf9338c79f3df9dc55f2.jpg");
 Addomain4.setad (FALSE);

 Adlist.add (ADDOMAIN4);
 ADDomain adDomain5 = new ADDomain ();
 Addomain5.setid ("108078");
 Addomain5.setdate ("March 8");
 Addomain5.settitle ("I have only the same surname as the order Plan");
 Addomain5.settopicfrom ("Big Bear"); Addomain5.settopic ("I want to know what is the relationship between the Fox and the plan?"
 ”");
 AdDomain5. Setimgurl ("/0bd162d9f2d3572c7dad11ba8913632762d0c30d.jpg"); Addomain5.setad (TRUE);

 The representative is the advertisement Adlist.add (ADDOMAIN5);
 return adlist;
 }

Viewpager logical Processing

1. Fill data (custom adapter)

2. Set page Toggle Listener Events

3. Set the Viewpager Click event in the Instantiateitem method in the custom adapter

Here our pictures are downloaded from the Internet, using the Universal-image-loader-1.8.6-with-sources.jar class library, you can implement the asynchronous loading of pictures, the specific use of view code.

Finally give the complete code:

/bannerautoscrolldemo/src/com/xiaowu/banner/demo/mainactivity.java

Package Com.xiaowu.banner.demo;
Import Java.io.File;
Import java.util.ArrayList;
Import java.util.List;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.ScheduledExecutorService;

Import Java.util.concurrent.TimeUnit;
Import android.app.Activity;
Import Android.graphics.Bitmap;
Import Android.os.Bundle;
Import Android.os.Handler;
Import android.os.Parcelable;
Import Android.support.v4.view.PagerAdapter;
Import Android.support.v4.view.ViewPager;
Import Android.support.v4.view.ViewPager.OnPageChangeListener;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.view.ViewGroup;
Import Android.widget.ImageView;
Import Android.widget.ImageView.ScaleType;

Import Android.widget.TextView;
Import Com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
Import Com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
Import com.nostra13.universalimageloader.core.DisplayImageOptions; Import Com.nostra13.universalimageloader.Core.
Imageloader;
Import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
Import Com.nostra13.universalimageloader.core.assist.ImageScaleType;

Import Com.nostra13.universalimageloader.core.assist.QueueProcessingType; public class Mainactivity extends activity {public static String Image_cache_path = "Imageloader/cache";//Picture cache path P
 Rivate Viewpager Adviewpager; Private list<imageview> imageviews;//sliding picture collection private list<view> dots;

 Picture title body of those points private list<view> dotlist;
 Private TextView tv_date;
 Private TextView Tv_title;
 Private TextView Tv_topic_from;
 Private TextView tv_topic; private int currentitem = 0;
 The index number//definition of the current picture five points private View dot0;
 Private View dot1;
 Private View Dot2;
 Private View dot3;

 Private View Dot4;

 Timed task private Scheduledexecutorservice scheduledexecutorservice;
 Load the picture asynchronously Imageloader Mimageloader;

 Private displayimageoptions options; Carousel Banner Data Private list<addomain> AdlisT Private Handler Handler = new Handler () {public void Handlemessage (Android.os.Message msg) {Adviewpager.setcurrentitem
 (CurrentItem);
 };

 };
 @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
 Setcontentview (R.layout.activity_main);

 Initialize Initimageloader () before using Imageloader;
 Get Picture Load Instance Mimageloader = Imageloader.getinstance (); options = new Displayimageoptions.builder (). Showstubimage (r.drawable.top_banner_android). Showimageforemptyuri ( r.drawable.top_banner_android). Showimageonfail (r.drawable.top_banner_android). Cacheinmemory (True). CacheOnDisc (

 true). Bitmapconfig (Bitmap.Config.RGB_565). Imagescaletype (imagescaletype.exactly). build ();

 Initaddata ();
 Startad (); }/** * Initialize Imageloader/private void Initimageloader () {File Cachedir = com.nostra13.universalimageloader.utils.

 Storageutils. Getowncachedirectory (Getapplicationcontext (), Image_cache_path); Displayimageoptions defaultoptions = new DisplaYimageoptions.builder (). Cacheinmemory (True). Cacheondisc (True). Build (); imageloaderconfiguration config = new Imageloaderconfiguration.builder (this). Defaultdisplayimageoptions (  defaultoptions). MemoryCache (New Lrumemorycache (* 1024 * 1024)). memorycachesize (* 1024 * 1024). Disccachesize (32 * 1024 * 1024). Disccachefilecount. Disccache (New Unlimiteddisccache (Cachedir)). ThreadPriority (Thread.NORM_

 PRIORITY-2). Tasksprocessingorder (Queueprocessingtype.lifo). build ();
 Imageloader.getinstance (). init (config);

 /** * Initialization ad data/private void Initaddata () {//advertising data Adlist = Getbannerad ();

 Imageviews = new arraylist<imageview> ();
 Dot dots = new arraylist<view> ();
 Dotlist = new arraylist<view> ();
 Dot0 = Findviewbyid (r.id.v_dot0);
 DOT1 = Findviewbyid (R.ID.V_DOT1);
 Dot2 = Findviewbyid (R.id.v_dot2);
 DOT3 = Findviewbyid (R.ID.V_DOT3);
 DOT4 = Findviewbyid (R.ID.V_DOT4);
 Dots.add (DOT0);
 Dots.add (DOT1);
 Dots.add (DOT2);
 Dots.add (DOT3); Dots. Add (DOT4);
 Tv_date = (TextView) Findviewbyid (r.id.tv_date);
 Tv_title = (TextView) Findviewbyid (r.id.tv_title);
 Tv_topic_from = (TextView) Findviewbyid (R.id.tv_topic_from);

 Tv_topic = (TextView) Findviewbyid (r.id.tv_topic);
 Adviewpager = (Viewpager) Findviewbyid (R.ID.VP);
 Adviewpager.setadapter (New Myadapter ())//Set the adapter that fills the Viewpager page//sets a listener that is called when the page in Viewpager changes
 Adviewpager.setonpagechangelistener (New Mypagechangelistener ());
 Adddynamicview (); } private void Adddynamicview () {////dynamically add picture and dot/Initialize picture resource for (int i = 0; i < adlist.size (); i++) {Imagevie
 W ImageView = new ImageView (this);
 Load the picture mimageloader.displayimage (Adlist.get (i) Getimgurl (), ImageView, options) asynchronously.
 Imageview.setscaletype (Scaletype.center_crop);
 Imageviews.add (ImageView);
 Dots.get (i). setvisibility (view.visible);
 Dotlist.add (Dots.get (i));
 }} @Override protected void Onresume () {super.onresume (); private void Startad () {scheduledexecutorservice = Executors.newsinglethreAdscheduledexecutor (); When the activity is displayed, toggle the picture display every two seconds scheduledexecutorservice.scheduleatfixedrate (new Scrolltask (), 1, 2, timeunit.seconds)
 ; Private class Scrolltask implements Runnable {@Override public void run () {synchronized (Adviewpager) {current
 Item = (currentitem + 1)% imageviews.size ();
 Handler.obtainmessage (). Sendtotarget ();
 }} @Override protected void OnStop () {super.onstop ();
 Stop switching Scheduledexecutorservice.shutdown () when the activity is not visible;

 Private class Mypagechangelistener implements Onpagechangelistener {private int oldposition = 0; @Override public void onpagescrollstatechanged (int arg0) {} @Override public void onpagescrolled (int arg0, float a
 RG1, int arg2) {} @Override public void onpageselected (int position) {CurrentItem = position;
 ADDomain ADDomain = adlist.get (position); Tv_title.settext (Addomain.gettitle ());
 Set the title Tv_date.settext (Addomain.getdate ());
 Tv_topic_from.settext (Addomain.gettopicfrom ()); Tv_topic. SetText (Addomain.gettopic ());
 Dots.get (oldposition). Setbackgroundresource (R.drawable.dot_normal);
 Dots.get (position). Setbackgroundresource (r.drawable.dot_focused);
 Oldposition = position;
 } private class Myadapter extends Pageradapter {@Override public int getcount () {return adlist.size (); @Override public Object Instantiateitem (viewgroup container, int position) {ImageView IV = imageviews.get (position)
 ;
 ((Viewpager) container). AddView (iv);
 Final ADDomain ADDomain = adlist.get (position);
 In this method, set the Click event of the picture Iv.setonclicklistener (new Onclicklistener () {@Override public void OnClick (View v) {//Process jump logic
 }
 });
 return IV;
 @Override public void Destroyitem (view arg0, int arg1, Object arg2) {(Viewpager) arg0). Removeview ((view) arg2);
 @Override public boolean isviewfromobject (View arg0, Object arg1) {return arg0 = = Arg1; @Override public void Restorestate (parcelable arg0, ClassLoader arg1) {} @Override public parcelable SavestatE () {return null;
 @Override public void Startupdate (view arg0) {} @Override public void finishupdate (view arg0) {}}/** * Carousel Broadcast Analog Data * * @return/public static list<addomain> Getbannerad () {list<addomain> adlist = new Array

 List<addomain> ();
 ADDomain addomain = new ADDomain ();
 Addomain.setid ("108078");
 Addomain.setdate ("March 4");
 Addomain.settitle ("I have only the same surname as the order Plan");
 Addomain.settopicfrom ("a curtilage"); Addomain.settopic ("I want to know what's the relationship between the Fox and the plan?"
 ");
 Addomain.setimgurl ("/d50735fae6cd7b8900d74cd40c2442a7d9330e29.jpg");
 Addomain.setad (FALSE);

 Adlist.add (ADDomain);
 ADDomain adDomain2 = new ADDomain ();
 Addomain2.setid ("108078");
 Addomain2.setdate ("March 5");
 Addomain2.settitle ("I have only the same surname as the order Plan");
 Addomain2.settopicfrom ("Little Witch"); Addomain2.settopic ("I want to know what is the relationship between the Fox and the plan?"
 ”");
 AdDomain2. Setimgurl ("/eaf81a4c510fd9f9a1edb58b262dd42a2934a45e.jpg");
 Addomain2.setad (FALSE);

 Adlist.add (adDomain2);
 ADDomain adDomain3 = new ADDomain ();
 Addomain3.setid ("108078"); AdDoMain3.setdate ("March 6");
 Addomain3.settitle ("I have only the same surname as the order Plan");
 Addomain3.settopicfrom ("Xu Dong"); Addomain3.settopic ("I want to know what is the relationship between the Fox and the plan?"
 ”");
 AdDomain3. Setimgurl ("/8718367adab44aed22a58aeeb11c8701a08bfbd4.jpg");
 Addomain3.setad (FALSE);

 Adlist.add (adDomain3);
 ADDomain adDomain4 = new ADDomain ();
 Addomain4.setid ("108078");
 Addomain4.setdate ("March 7");
 Addomain4.settitle ("I have only the same surname as the order Plan");
 Addomain4.settopicfrom ("small soft"); Addomain4.settopic ("I want to know what is the relationship between the Fox and the plan?"
 ”");
 AdDomain4. Setimgurl ("/a686c9177f3e670932e4cf9338c79f3df9dc55f2.jpg");
 Addomain4.setad (FALSE);

 Adlist.add (ADDOMAIN4);
 ADDomain adDomain5 = new ADDomain ();
 Addomain5.setid ("108078");
 Addomain5.setdate ("March 8");
 Addomain5.settitle ("I have only the same surname as the order Plan");
 Addomain5.settopicfrom ("Big Bear"); Addomain5.settopic ("I want to know what is the relationship between the Fox and the plan?"
 ”");
 AdDomain5. Setimgurl ("/0bd162d9f2d3572c7dad11ba8913632762d0c30d.jpg"); Addomain5.setad (TRUE);

 The representative is the advertisement Adlist.add (ADDOMAIN5);
 return adlist;

 }

}

SOURCE Download: Http://xiazai.jb51.net/201612/yuanma/AndroidBannerAutoScroll (jb51.net). rar

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.