Android uses Viewpager to achieve infinite sliding effect _android

Source: Internet
Author: User
Tags object object

Objective

In fact, think carefully about the principle is quite simple. It's just when we slide to the last page and then slide backwards to the first page, and when we slide to the first page and slide forward, we navigate to the last page.

However, I believe many friends have encountered this problem: the view of the excessive effect is not natural.

Small series is also through Baidu and Google to find a lot of solutions, experimented with a lot of methods, summed up a relatively good method, next to you to share the sliding effect, implementation details and some of the pits.

1. Infinite sliding effect (left and right infinite sliding)

Prepared in advance 2 slide picture (have want to experiment of small partner, own picture Ah, small series does not provide ... )


Run effect Diagram (infinite loop around):

In order to display more intuitive, the small series only used 2 pictures.

2. Code implementation

(1) XML layout file for activity (very simple layout)

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"
 android:layout_width= "Match_ Parent "
 android:layout_height=" match_parent ">

 <android.support.v4.view.viewpager
  android:id= "@+id/view_pager"
  android:layout_width= "match_parent"
  android:layout_height= "200DP"/>
</ Relativelayout>

(2) Activity

public class Mainactivity extends Appcompatactivity {

 private viewpager Mviewpager;
 Private Viewpageradapter Madapter;
 Private int[] images; The picture resource array

 @Override
 protected void onCreate (Bundle savedinstancestate) {
  super.oncreate ( Savedinstancestate);
  Setcontentview (r.layout.activity_main);
  Initview (); Initialize View
  initdata ()///initialization Data
 }

 /**
  * Initialization view/
 private void Initview () {
  Mviewpager = (Viewpager) Findviewbyid (R.id.view_pager);
 }

 /**
  * Initialization data *
 /private void InitData () {
  images = new int[]{r.mipmap.image1, r.mipmap.image2};
  Madapter = new Viewpageradapter (this, images);
  Mviewpager.setadapter (madapter);

  Position the Viewpager to the middle page (1th element of the picture resource array near SHORT.MAX_VALUE/2)
  //Purpose: 1. The number of pictures >1 only 2. Navigate to the middle page and both left and right can be slippery
  if ( Images.length > 1) {
   Mviewpager.setcurrentitem ((SHORT.MAX_VALUE/2)/images.length) * images.length, FALSE); c28/>}}}

(3) Viewpageradapter

/** * @ClassName: Viewpageradapter * @Description: Viewpager Adapter * @Author Wangnan * @Date 2016/9/1/public class V
 Iewpageradapter extends pageradapter{private context mcontext; Private int[] mimages; Picture resource ID Array private list<imageview> mimageviews;
  ImageView Set Public viewpageradapter (context context, int[] images) {Mcontext = context;
  Mimages = images;
  Mimageviews = new arraylist<> ();
 Initimageviews (mimages); /** * Initialize imageviews collection * @param imageids/private void Initimageviews (int[) imageids) {///based on picture resource array Imagev
   Iews collection for (int i = 0; i < imageids.length i++) {ImageView Mimageview = new ImageView (mcontext);
   Mimageview.setimageresource (Imageids[i]);
   Mimageview.setscaletype (ImageView.ScaleType.CENTER_CROP);
  Mimageviews.add (Mimageview); The number of pictures in the//Imageviews collection is problematic in [2,3], and recursively populated again if (Mimageviews.size () > 1 && mimageviews.size () < 4) {I
  Nitimageviews (Imageids); @Override public int gEtcount () {return mimageviews.size () <=1 mimageviews.size (): Short.max_value;
 @Override public boolean isviewfromobject (view view, Object object) {return view = = object; @Override public Object Instantiateitem (viewgroup container, int position) {ImageView Mimageview = Mimageviews.get
  (Position% mimageviews.size ());
  Container.addview (Mimageview);
 return mimageview; @Override public void Destroyitem (ViewGroup container, int position, object object) {Container.removeview (View) OB
 ject); }
}

The specific need to explain the place, the code has done a corresponding comment, no longer to explain, but the following small series will explain the encounter of the two pit points.

3. Detail Pit

believe that in the implementation of the small series before, someone on the internet also found a lot of similar implementation. The next thing to talk about is--to "These similar implementations" step on the pit.

1. Exception:java.lang.IllegalStateException:The specified child already has a parent. You are must call Removeview () on the child ' s parent.

Reason: the picture resource is less than 4, corresponding generation ImageView also less than 4.

It is well known that ViewPager 2~3 pages are generally maintained, if there are only 3 ImageView , this is likely to happen, after 3 Page pages are generated and ready to generate page 4th, the first page that should have been removed has not been removed, the system will report an exception and give you such a hint: Must call Removeview () in the child's parent first (meaning that you remove the front page View from the front page and add the child View to page 4th).

Solution: in only 1 pictures, can not slide, temporarily do not handle; if there is a 2~3 picture, the recursive increase to more than or equal to 4 ImageView (below the small series to solve the problem of the code).

 /**
  * Initialize imageviews set
  * @param imageids
 /private void Initimageviews (int[) imageids) {

  ... The

  number of pictures in the//Imageviews collection is problematic in [2,3], and recursively populated again
  if (Mimageviews.size () > 1 && mimageviews.size () < 4 {
   initimageviews (imageids);
  }
 }

2. The sliding effect appears to be confusing (the following will be accompanied by a messy effect chart)

Reason: ViewPager There is a problem with the source itself-the data range is out of bounds.

The way to get the number of pages in a small weave ViewPager is to write this:

 @Override public
 int GetCount () {return
  mimageviews.size () <=1? Mimageviews.size (): short.max_value;< c18/>}

Less than 1 o'clock, the page does not slide, do not need to expand the number of pages;

Greater than 1 o'clock, take Short the maximum value range of 32767 (we will have more than 3W pages, but not the same, because Viewpager up to 3 pages)

Small knitting here is short, but the first to find a similar implementation of the Internet is all used Integer (Integer.max_value = 2147483647, that is, our viewpager will have about 2.1 billion pages), if used Integer , More attentive friends will find that sliding often occurs in confusion.

Page reverse rebound bug


When we let go, the page appears in reverse Bounce (1~2 page), which is inconsistent with our desired sliding effect.

This is one of the bugs, there are some not very good description of the slide bug, small series on the "Sliding chaos" this term to explain ...

Solution: Reduce the number of pages (small use of the substitution of the Short Integer page).

Specific bug-free thresholds, interested partners can go to the experiment, small series of test results are as follows:

Less than 8 million: basic no sliding bug;

10 million or so: Beginning to appear the current page positioning inaccurate bug, but there is no reverse rebound bug.

Summarize

The above is about Android using Viewpager to achieve infinite sliding effect of the entire content, I hope this article for everyone to develop the time can help, if there are questions can be exchanged message.

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.