Android uses Viewpager to implement automatic carousel _android

Source: Internet
Author: User
Tags int size

Many apps have implemented an automatic carousel like a boot page, and could not help thinking about modifying the code on yesterday's boot page to implement the carousel. In fact, only need to add a thread loop execution on the whole.

Project synchronized to: Https://github.com/nanchen2251/viewpagerDemo

The same first picture.

Directly on the code, the comments are full, I think this is more conducive to understanding.

Change the Adapter first.

Package Com.example.nanchen.taketurnplaydemo;
Import Android.support.v4.view.PagerAdapter;
Import Android.view.View;
Import Android.view.ViewGroup;

Import java.util.List;
 /** * Created by South Dust on 2016/7/10.
 * * public class Guidepageadapter extends Pageradapter {private list<view> viewlist;
 Public Guidepageadapter (list<view> viewlist) {this.viewlist = viewlist;
 /** * @return Number of pages returned * * @Override public int GetCount () {if (viewlist!= null) {//return viewlist.size ();

 The first modification, set the maximum rotation, equal to infinite loop return integer.max_value;
 return 0; /** * Determines whether the object generates an interface * @param view * @param Object * @return * * @Override public boolean isviewfromobject (View VI
 EW, object) {return view = = object; /** * Initialize Position interface * @param container * @param position * @return * * @Override public Object Instantiateit
 EM (viewgroup container, int position) {//second modification, the current data index to display is set length int newposition = position% viewlist.size (); Container.addview (viewlist.Get (newposition)); 

Return Viewlist.get (newposition);
Container.addview (Viewlist.get (position));
 return Viewlist.get (position); @Override public void Destroyitem (ViewGroup container, int position, object) {//third modification, the removed index is the length of the set int Newpo
 sition = position% viewlist.size ();

Container.removeview (Viewlist.get (newposition));
 Container.removeview (Viewlist.get (position));

 }

}

Looking at activity 

Package Com.example.nanchen.taketurnplaydemo;
Import android.content.Intent;
Import Android.os.Bundle;
Import Android.support.v4.view.ViewPager;
Import android.support.v7.app.AppCompatActivity;
Import Android.view.View;
Import Android.view.ViewGroup;
Import Android.view.Window;
Import Android.widget.ImageButton;
Import Android.widget.ImageView; 
Import Android.widget.LinearLayout;
Import java.util.ArrayList;
 
Import java.util.List; /** * Implement first boot page/public class Guideactivity extends appcompatactivity implements viewpager.onpagechangelistener{p
 Rivate Viewpager VP; private int []imageidarray;//image resource Array private list<view> viewlist;//Picture resource Collection Private viewgroup vg;//Place dot//Instantiate Origin VI
 EW private ImageView Iv_point;
 Private ImageView []ivpointarray; 

 Private Boolean islooper;
 The last page of the button private ImageButton ib_start;
 @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Supportrequestwindowfeature (Window.feature_no_title); Setcontentview (R.layout.activity_guide);
 Ib_start = (ImageButton) Findviewbyid (R.id.guide_ib_start); Ib_start.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {startactivity (new inte
 NT (Guideactivity.this,mainactivity.class));
 Finish ();
 }
 });
 Loading Viewpager initviewpager ();
 Load Bottom dot initpoint ();
 Modify add Settings Viewpager current page, in order to ensure the left and right Carousel Vp.setcurrentitem (5000000);
 Opens a thread that is used to loop new thread (new Runnable () {@Override public void run () {islooper = true;
  while (Islooper) {try {thread.sleep (2000);

  catch (Interruptedexception e) {e.printstacktrace (); Runonuithread (New Runnable () {@Override public void run () {/) This is the next page of the current page set Vp.setcurrentitem (vp.getcurrentite
  M () + 1);
 }
  });

 }}). Start (); /** * Load Bottom dot */private void Initpoint () {//here instantiate linearlayout VG = (viewgroup) Findviewbyid (r.id.guide_ll_point)
 ;
 Instantiate an array ivpointarray = new Imageview[viewlist.size () based on the number of item Viewpager; Loop New Bottom Dot ImageView, save the generated imageview to the array int size = Viewlist.size ();
 for (int i = 0;i<size;i++) {iv_point = new ImageView (this);
 Iv_point.setlayoutparams (New Viewgroup.layoutparams (20,20));
 Iv_point.setpadding (30,0,30,0);//left,top,right,bottom ivpointarray[i] = iv_point;
 The first page needs to be set to the selected state, where two different pictures are used if (i = = 0) {iv_point.setbackgroundresource (R.mipmap.full_holo);
 }else{Iv_point.setbackgroundresource (R.mipmap.empty_holo);
 //Add the ImageView in the array to the ViewGroup Vg.addview (ivpointarray[i));
 }/** * Load picture Viewpager/private void Initviewpager () {VP = (Viewpager) Findviewbyid (R.ID.GUIDE_VP);
 Materialized picture Resource Imageidarray = new INT[]{R.MIPMAP.GUIDE1,R.MIPMAP.GUIDE2,R.MIPMAP.GUIDE3};
 Viewlist = new arraylist<> ();
 Gets a layout parameter, set to full screen linearlayout.layoutparams params = new Linearlayout.layoutparams (
 Linearlayout.layoutparams.match_parent,linearlayout.layoutparams.match_parent);
 Loop create view and add to the collection int len = imageidarray.length; for (int i = 0;i<len;i++) {//new ImageView and set full-screen and picture resources IMageview ImageView = new ImageView (this);
 Imageview.setlayoutparams (params); 
 Imageview.setbackgroundresource (Imageidarray[i]);
 Adding ImageView to the Set Viewlist.add (ImageView);
 When the//view collection is initialized, set the adapter Vp.setadapter (new Guidepageadapter (viewlist));

 Set Sliding monitoring Vp.setonpagechangelistener (this); @Override public void onpagescrolled (int position, float positionoffset, int positionoffsetpixels) {}/** * after sliding Monitor * @param position * * @Override public void onpageselected (int position) {//modify all position length int newposition = pos
 Ition% viewlist.size ();
 Loop to set the current page's tag graph int length = imageidarray.length;
 for (int i = 0;i<length;i++) {ivpointarray[newposition].setbackgroundresource (R.mipmap.full_holo);
 if (newposition!= i) {ivpointarray[i].setbackgroundresource (R.mipmap.empty_holo);
}////Loop set the current page's tag graph//int length = Imageidarray.length; for (int i = 0;i<length;i++) {//Ivpointarray[position].setbackgroundresource (R.mipmap.full_holo);//if (position != i) {//IVpointarray[i].setbackgroundresource (R.mipmap.empty_holo); /////Determine if it is the last page, if the display button//if (position = = imageidarray.length-1) {//Ib_start.setvisibility (view.visible);//}e

 LSE {//ib_start.setvisibility (View.gone);//} @Override public void onpagescrollstatechanged (int state) {}}

What's worth mentioning in the activity is that we often use the update UI in actual Android development, where we used to be handler, and here's another way to implement it Runonuithread (), Requires an implementation class that implements the Runnable interface as a parameter,

XML is just as simple

<?xml version= "1.0" encoding= "Utf-8"?> <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= ". Guideactivity "> <relativelayout android:layout_width=" match_parent "android:layout_height=" 200DP "> < Android.support.v4.view.ViewPager android:id= "@+id/guide_vp" android:layout_width= "Match_parent" Android:layout_ height= "Match_parent" > </android.support.v4.view.ViewPager> <linearlayout android:id= "@+id/guide_ll_
 Point "android:layout_width=" Match_parent "android:layout_height=" wrap_content "android:orientation=" Horizontal " Android:layout_alignparentbottom= "true" android:paddingbottom= "10DP" android:gravity= "Center_horizontal" > < /linearlayout> <imagebutton android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android : id= "@+id/guide_ib_start" ANDROID:SRc= "@mipmap/btn_start" android:layout_centerhorizontal= "true" android:layout_above= "@+id/guide_ll_point" Android: 
 Background= "@null" android:visibility= "Gone"/> </RelativeLayout> </RelativeLayout>

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.