Using Rxjava and Viewpager to implement the Carousel diagram in Android _android

Source: Internet
Author: User
Tags static class time interval

Objective

Many people want to implement the Carousel diagram will think of using Viewpager + handler to complete the effect of the carousel diagram. But with the rapid development of Rxjava, Rxjava can be used instead of handler to accomplish such a task.

Here we will introduce how to implement Rxjava+viewpager's Carousel diagram.

The effect chart is as follows

Operation of Viewpager

Speaking of Viwepager should everyone is not unfamiliar, it can be combined with ordinary view can also be combined with fragment use. In this I also do not have the use of its methods too much introduction. Start by introducing the method of carousel directly.

Common Wheel-seeding operations

Private class Imageadapter extends pageradapter{

 private arraylist<imageview> viewlist;

 Public Imageadapter (arraylist<imageview> viewlist) {
  this.viewlist = viewlist;
 }

 @Override public
 int GetCount () {
  //set to maximum, so that the user does not see the boundary return
  integer.max_value;
 }
 ....
}
 private static class ImageHandler extends handler{... @Override public void Handleme
  Ssage (Message msg) {super.handlemessage (msg);
  Check Message Queuing and remove unsent messages, primarily to avoid problems with duplication of messages in complex environments.
  if (Activity.handler.hasMessages (msg_update_image)) {activity.handler.removeMessages (msg_update_image);
    Switch (msg.what) {case msg_update_image:currentitem++;
    Activity.viewPager.setCurrentItem (CurrentItem);
    Prepare for next play activity.handler.sendEmptyMessageDelayed (Msg_update_image, Msg_delay);
   Break
   Case Msg_keep_silent://The break is paused as long as the message is not sent;
    Case MSG_BREAK_SILENT:activity.handler.sendEmptyMessageDelayed (Msg_update_image, Msg_delay);
   Break
    Case msg_page_changed://Record the current page number to prevent the page from displaying incorrectly when playing.
    CurrentItem = MSG.ARG1;
   Break
  Default:break; 
}
 }
 ...
}

The above is the more common Carousel Map Code, I just look for the internet casually. First of all, its code getCount() will pageradapter back to one of Integer.MAX_VALUE; its purposes is to let the picture continue to play, but in some extreme cases still crash, and it returned to the amount of too much to some extent memory also caused a large consumption. Second, we can see the handler code is extremely jumbled, not only more and more logic is also troublesome. Now we're going to optimize for the problems we just made.

Better wheel-seeding operations

Better unlimited Playback: When you set the page card View list, add a page card to the front and back. Add the last picture to the front and the 1th picture at the end. Then, whenever you switch to the front page card, replace the 2nd page card, and replace it with the 2nd card whenever you switch to the last page card. This creates coherence, and naturally enables the function of infinite sliding.

1 when you set up a list of Viewpager views, add a page card before and after.

for (int i = 0; I < count + 2; i++) {
 if (i = = 0) {///The last page set cost to the final page
  Glide.with (context).
    Load (Imagetitlebeanlist.get (count-1). Getimageurl ()). into (ivimage);
  Tvtitle.settext (Imagetitlebeanlist.get (count-1). GetTitle ());
 else if (i = = count + 1) {//The last page set the cost to the top page
  glide.with (context).
    Load (imagetitlebeanlist.get (0). Getimageurl ()). into (ivimage);
  Tvtitle.settext (Imagetitlebeanlist.get (0). GetTitle ());
 else {
  Glide.with (context).
    Load (Imagetitlebeanlist.get (i-1). Getimageurl ()). into (ivimage);
  Tvtitle.settext (Imagetitlebeanlist.get (i-1). GetTitle ());
 Add a set of view to the View list
 viewlist.add (view)

2 in the monitor Viewpager card state change, when sliding to the 1th page card replaced by the penultimate page card, when sliding to the last page card replaced by the 2nd page card.

@Override public
void onpagescrollstatechanged (int state) {
 switch (state) {
  //idle
  case Viewpager.scroll_state_idle:
   //"cynical"
   if (vpimagetitle.getcurrentitem () = = 0) {
    Vpimagetitle.setcurrentitem (count, false);
   else if (vpimagetitle.getcurrentitem () = = count + 1) {
    Vpimagetitle.setcurrentitem (1, false);
   }
   CurrentItem = Vpimagetitle.getcurrentitem ();
   break;
 }
}

Handler should now be replaced by Rxjava.

Interval operator

Creates a observable that emits an integer sequence at a fixed time interval


The interval operator returns a observable that emits an infinitely incremented sequence of integers at a fixed time interval.


Rxjava this operator as a interval method. It accepts a parameter that represents the interval and a parameter that represents the time unit.

Javadoc:interval(long,TimeUnit)

Javadoc:interval(long,TimeUnit,Scheduler)

Interval is performed on the computation scheduler by default. You can also pass an optional scheduler parameter to specify the scheduler.

Replace handler with Rxjava

public void Start () {
 mviewpagersubscribe = Observable.interval (5, 5, timeunit.seconds)//5s delay, 5s cycle time
  . Subscribeon (Androidschedulers.mainthread ())
  . Observeon (Androidschedulers.mainthread ())
  . Subscribe (NEW Action1<long> () {
   @Override public
   void Call (Long along) {
    //Carousel Operation
    if (Mweeklymovieinfos!= Null && mweeklymovieinfos.size () > 0 && isautoplay) {
     mcurrentpage++;
     Mweeklyviewpager.setcurrentitem (Mcurrentpage);}}
  );

For a better user experience, you should stop the automatic carousel while the user is sliding

Mpager.setontouchlistener (New View.ontouchlistener () {
 @Override public
 boolean Ontouch (View V, motionevent Event) {
 //monitor Viewpager Touch event, cancel registration when user presses, register switch when user hands up
  (Event.getaction ()) {case
   Motionevent.action_down:
    Stop ();
    break;
   Case MOTIONEVENT.ACTION_UP:
    start ();
    break;
  return false;
 }});

public void Stop () {
 if (mviewpagersubscribe.isunsubscribed ()) { 
  mviewpagersubscribe.unsubscribe ()}
}

Summarize

This article is a summary of the Viewpager to realize the carousel graph. First of all, we propose a better method of wheel-seeding, in fact, explain the use of the interval operator in Rxjava, and finally replace the handler with this operator to achieve the perfect carousel map. The above is the entire content of this article, I hope the content of this article can be helpful to everyone, if you have questions you can message exchange.

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.