I'll teach you how to implement banner carousel with Viewpager customization _android

Source: Internet
Author: User
Tags manual message queue

Welcome to the Android Open Source network framework Nohttp:https://github.com/yanzhenjie/nohttp

We are in the actual development, a lot of apps are doing an ad carousel (maybe a picture, maybe other view), many students are using someone else's encapsulation or directly using Viewpager to change their own, but someone may not understand the principle inside, or someone has encountered a gesture sliding conflict. We're going to use 150 lines of code today to implement a custom advertisement the carousel does not interfere with the original view slide event.
This example code source and demo transmission door

Effect Demo

Requirements Analysis, Solutions

The most important features of the wheel-seeding device are: automatic scrolling, manual sliding, scrolling direction, and the time each item displays. So we design the following methods for external invocation:

/**
 * Set the playback time for each item, default 3000 milliseconds
 *
/public void setshowtime (int showtimemillis);

/**
 * Set scrolling direction, default to left scroll * * * public
void Setdirection (Direction Direction);

/**
 * Start automatic scrolling * * Public
void Start ();

/**
 * Stop automatic scrolling
 *
/public void Stop ();

/**
 * Play on the previous *
/public void previous ();

/**
 * Play next
 *
/public void next ();

Carefully read the above method students will find, and our analysis think, but also lack of a manual sliding method, we know that gesture sliding is sure to use Ontouch and other methods, so we think of V4 under the Viewpager with sliding effect, and can code control to jump to an item. So our custom view inheritance Viewpager is not a perfect solution.
We see that the above method has a direction class, this class is not a system, is the Darwin custom Direction control enumeration, the most common carousel direction is nothing more than the left and right carousel (up and down this time not discussed), the code is as follows:

public enum Direction {
 /**
 * Move to the left, play the next one should be on the right side
 ,

 /**
 * Move to the right, play the next one should be left
 Right
}

How custom view is implemented and how it works

The above analysis to need to inherit viewpager,so we first combine the above several methods to the complete code:

 public class Autoplayviewpager extends Viewpager {public Autoplayviewpager (context Co
 ntext) {super (context);
 Public Autoplayviewpager (context, AttributeSet attrs) {Super (context, attrs);
 /** * Play time/private int showTime = 3 * 1000;

 /** * Rolling direction/private Direction Direction = Direction.left; /** * Set playback time, default 3 seconds * * @param showtimemillis millisecond/public void setshowtime (int showtimemillis) {this.showtime = Show
 time; /** * Set scrolling direction, default left scroll * * @param direction direction/public void Setdirection (direction direction) {This.direction =
 Direction /** * Start/public void Start () {//TODO to be implemented start play}/** * Stop/public void Stop () {//TODO pending stop play}/
 * * Play on the previous/public void previous () {//TODO pending playback previous}/** * Play next/public void Next () {//Todo play next  public enum Direction {/** * move to the left, play should be on the right side,/** * to the right, play should be the left side of the * *} 

Setshowtime (int showtimemillis) method and Setdirection (Direction Direction) is to record a certain state, it is now simple to implement, the focus is to start playing and stop playing.

Principle analysis and realization of timing wheel-seeding

High energy ahead, everybody reader be careful not to lose the trousers. Now we use Viewpager the most important thing is to automatically play, so we need a timer to perform the task, but this way we have to use handler, a bit of a fuss. Here are two ways to introduce view:

The thread will be added to the message queue, which will run on the UI thread (the main thread). Public
Boolean post (Runnable action);

The thread will be added to the message queue and run after the specified time, and the thread will run on the UI thread (the main thread). Public
Boolean postdelayed (Runnable action, long Delaymillis);

See the second method is like the enlightened ah there is wood, since it is all view all the way, Viewpager must have ah, so can not be in the main thread scheduled to release a task? So we write a runnable here to do this timed task.

/**
 * Player/
private Runnable player = new Runnable () {
 @Override public
 void Run () {Play
 ( direction);
 }
;

Here we see a play (direction), the way we do it, let's put this method aside for a moment, and we'll see how we can use this private Runnable player to finish starting and stopping playback.

Implementation starts and stops playing

We use postdelayed (Runnable action, long Delaymillis) when we start playing to let the currently displayed picture show the Showtime time, so the method triggers the private after Showtime time Runnable Player:

/**
 * Start
/public void Start () {
 postdelayed (player, showTime);
}

Stop playing, we have to cancel this thread on the line, so the implementation of the Stop method is:

/**
 * Stop
/public void Stop () {
 removecallbacks (player);
}

But in order to prevent the developer from constantly invoking the Start method to cause the death card, we do an optimization in start, each time before star to remove the private runable player, so the complete code of the Start method is:

/**
 * Start
/public void Start () {
 stop ();
 Postdelayed (player, showTime);
}

Core Focus: How to play the previous one and the next one according to the direction

The core and focus of this example comes, now go back to realize just put on the play (direction); method, it should be based on the direction of playback to play the previous and next, we specifically look at the code, especially to savor the comments OH:

/**
 * Perform playback
 *
 * @param direction playing direction
/private synchronized void play (direction direction) {
 / /Get Viewpager adapter
 pageradapter pageradapter = Getadapter ();
 if (pageradapter!= null) {//blank
 //Item quantity
 int count = Pageradapter.getcount ();
 What is the number of Viewpager now displayed?
 int currentitem = Getcurrentitem ();
 switch (direction) {case
  left://scroll to the left, Currentitem+1 play the next
  currentitem++;

  If + to the last one, go to the first
  if (CurrentItem >= count)
   currentitem = 0;
  break;
  Case right://Scroll to the right, currentItem-1 play the previous
  currentitem--;

  If-to the lower one, just to the last
  if (CurrentItem < 0)
   CurrentItem = count-1;
  break;
 Setcurrentitem (CurrentItem)//Play the position item according to direction

 //This is the focus of the loop playback, once each playback is completed, open a timed task
 again Start ();
}

In fact, we have achieved the carousel, but we found a situation when using the finger, when we have just slipped a sheet, and then the second came out again, not suspense, the reason is that our fingers sliding when the private Runnable player this task does not stop, So we stop the player while the fingers are slipping, and turn on the player again when the finger is loose:

@Override
protected void Onfinishinflate () {
 Addonpagechangelistener (new Onpagechangelistener () {
 @ Override public
 void onpagescrolled (int position, float positionoffset, int positionoffsetpixels) {
 }

 @ Override public
 void onpageselected (int position) {
 }

 @Override public
 Void onpagescrollstatechanged (int state) {
  if (state = = Scroll_state_idle)
  start ();
  else if (state = = scroll_state_dragging)
  stop ();}}
 );


Some students may not know why it is not in the construction method to Addonpagechangelistener in the onfinishinflate, because this method will be called after the view is loaded, so it is reasonable to do some initialization work here.
The complete code for the custom Viewpager is as follows:

Package Com.yolanda.autoviewpager;
Import Android.content.Context;
Import Android.support.v4.view.PagerAdapter;
Import Android.support.v4.view.ViewPager;

Import Android.util.AttributeSet; /** * <p> Custom advertising carousel with Viewpager.
 </p>. 
 * * @author Yolanda;
 * * public class Autoplayviewpager extends Viewpager {public Autoplayviewpager (context) {super (context);
 Public Autoplayviewpager (context, AttributeSet attrs) {Super (context, attrs);
 /** * Play time/private int showTime = 3 * 1000;
 /** * Rolling direction/private Direction Direction = Direction.left; /** * Set playback time, default 3 seconds * * @param showtimemillis millisecond/public void setshowtime (int showtimemillis) {this.showtime = Show
 time; /** * Set scrolling direction, default left scroll * * @param direction direction/public void Setdirection (direction direction) {This.direction =
 Direction
 /** * Start/public void Start () {Stop ();
 Postdelayed (player, showTime); /** * Stop/public void Stop () {removecallbacks (plAyer);
 /** * Plays the previous/public void previous () {if (direction = = Direction.right) {play (direction.left);
 else if (direction = = Direction.left) {play (direction.right);
 }/** * Play next/public void next (direction); /** * Perform playback * * @param direction playing direction/private synchronized void play (direction direction) {Pageradapter pager
 Adapter = Getadapter ();
  if (pageradapter!= null) {int count = Pageradapter.getcount ();
  int currentitem = Getcurrentitem ();
   switch (direction) {case left:currentitem++;
   if (CurrentItem > Count) currentitem = 0;
  Break
   Case right:currentitem--;
   if (CurrentItem < 0) CurrentItem = count;
  Break
 } setcurrentitem (CurrentItem);
 Start ();
 /** * Player/private Runnable player = new Runnable () {@Override public void run () {play (direction);

 }
 }; public enum Direction {/** * move to the left, play should be on the right side,/** * to the right, play should be the left side of the * * @Override proteCTED void Onfinishinflate () {super.onfinishinflate (); Addonpagechangelistener (New Onpagechangelistener () {@Override public void onpagescrolled (int position, float position Offset, int positionoffsetpixels) {} @Override public void onpageselected (int position) {} @Override Publi
  c void onpagescrollstatechanged (int state) {if (state = = Scroll_state_idle) start ();
  else if (state = = scroll_state_dragging) stop ();
 }
 });


 }
}

How to use

In fact, we did not do much to viewpager interference, so we use and native of no difference. Here are a few places to pay attention to also write out, lest someone trample on the pit.

If you use a custom Viewpager

Autoplayviewpager autoplayviewpage = (autoplayviewpager) Findviewbyid (R.id.view_pager);
Autoplayviewpage.setadapter (banneradapter);

The following two methods are not required because there is a default value
autoplayviewpage.setdirection (AutoPlayViewPager.Direction.LEFT);/Set playback direction
Autoplayviewpage.setcurrentitem (200); Set the time for each item display

Autoplayviewpage.start ()//Start Carousel

How to optimize adapter

In fact, we see that we have called a star method more, but not enough, we have to do a little bit of things in the adapter. In order to allow the carousel to loop indefinitely, we return the maximum value of int in GetCount:

@Override public
int GetCount () {return
 Resids = = null 0:integer.max_value;
}

Resids is our data source. After this count, our Instantiateitem () method also needs to be modified, otherwise there will be a subscript out of bounds of the exception, we have to do after the position to deal with:

@Override public
Object instantiateitem (viewgroup container, int position) {
 position = position% resids.size () ;
 Object Xxoo = resids.get (position);
 ...
}

This example code Source: Http://xiazai.jb51.net/201609/yuanma/AutoViewPager (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.

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.