Android viewpager implement banner loop playback _android

Source: Internet
Author: User
Tags object object

The origin of the problem
in the project, sometimes need to implement a picture carousel effect, used to show banner. At the same time, the picture can be looped, and there is a row of dots below to indicate which page the current carousel is on.

The following figure:


Analysis
· The number of pictures will change, and the number of small dots will follow the number of pictures change
· The layout of each page is the same. The change is the number of small dots, so need to use code to dynamically generate small dots

Coding
layout
First complete the mainactivity layout activity_main.xml

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http:// Schemas.android.com/tools "android:id=" @+id/container "android:layout_width=" Match_parent "android:layout_height=" "Match_parent" > <!--viewpager--> <android.support.v4.view.viewpager android:id= "@+id/viewpager" Andr Oid:layout_width= "Fill_parent" android:layout_height= "180dip"/> <linearlayout android:layout_width= "Fill_" Parent "android:layout_height=" wrap_content "android:layout_alignbottom=" @id/viewpager "android:background=" #  44000000 "android:gravity=" center "android:orientation=" vertical "android:padding=" 5dip "> <!--Banner text description --> <textview android:id= "@+id/tv_banner_text_desc" android:layout_width= "Wrap_content" Android:layout_h eight= "Wrap_content" android:textcolor= "@android: Color/white"/> <!--Dot's parent control--> <linearlayout and Roid:id= "@+id/ll_dot_group" android:layout_width= "Fill_parenT "android:layout_height=" wrap_content "android:layout_gravity=" Center_horizontal "android:layout_margintop=" 5dip "Android:gravity=" center_horizontal "android:orientation=" horizontal "> </LinearLayout> </linearlayo

 Ut> </RelativeLayout>

Because small dots have two states, one is the state with the enable to true, and the state with the enable false. So you need to write a selector XML configuration file for small dots, and put them in the Drawable folder. Here, name it dot_bg_selector.xml.

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

 <item android:drawable= "@drawable/point_bg_enable" android:state_enabled= "true" ></item >
 <item android:drawable= "@drawable/point_bg_normal" android:state_enabled= "false" ></item>

</selector>

You need to write two more XML files as a small dot in different states of the style
Point_bg_enable.xml

<?xml version= "1.0" encoding= "Utf-8"?> <shape xmlns:android=
"http://schemas.android.com/apk/res/" Android "
 android:shape=" Oval ">
 <corners android:radius=" 0.5dip "/> <solid-android:color=
 "#aaFFFFFF"/>
</shape>

Point_bg_normal.xml

<?xml version= "1.0" encoding= "Utf-8"?> <shape xmlns:android=
"http://schemas.android.com/apk/res/" Android "
 android:shape=" Oval ">
 <corners android:radius=" 0.5dip "/> <solid android:color=
 " #55000000 "/>
</shape>

Prepare picture Resources
I placed several pictures in the res\drawable-hdpi folder to demonstrate


Start encoding
code with a detailed comment, you can see. There is no clear welcome to point out

Package Com.owen.adbanner;
Import java.util.ArrayList;

Import java.util.List;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.os.SystemClock;
Import Android.support.v4.view.PagerAdapter;
Import Android.support.v4.view.ViewPager;
Import Android.view.View;
Import Android.view.ViewGroup;
Import Android.widget.ImageView;
Import Android.widget.LinearLayout;
Import Android.widget.Toast;
Import Android.widget.LinearLayout.LayoutParams;

Import Android.widget.TextView; /** * Viewpager Implementation banner Loop rolling * @author Owen/public class Mainactivity extends activity {/** Viewpager


 W's container * * Private list<imageview> imageviewcontainer = null;

 /** the index of the last selected dot, the default value is 0 */private int predotposition = 0; /** Banner Text description array/private string[] Bannertextdescarray = {"Gong Li is not vulgar, I can not vulgar", "Hackberry back again, and then sing the classic old songs of the People Chorus", "The Secret of Beijing film How to Rise

 Level "," Music network TV version of the big delivery "," blood cock Silk's anti-Kill "};

 /** Banner Scroll thread is destroyed flag, default does not destroy/private Boolean isstop = false;
 /** Banner to toggle the next page interval * *Private long scrolltimeoffset = 5000;

 Private Viewpager Viewpager;

 /** Banner Text description Display control/private TextView Tvbannertextdesc;

 /** small dot of the parent control/private LinearLayout lldotgroup;
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);

  Setcontentview (R.layout.activity_main);
  Initview ();
 Startbannerscrollthread (); /** * Open Banner scrolling thread/private void Startbannerscrollthread () {New Thread (new Runnable () {@Override Pub

     LIC void Run () {while (!isstop) {//Every two seconds sends a message to the main thread, updating the Viewpager interface Systemclock.sleep (Scrolltimeoffset);
       Runonuithread (New Runnable () {public void run () {int newindex = Viewpager.getcurrentitem () + 1;
      Viewpager.setcurrentitem (NewIndex);
    }
     });
 }}). Start ();
  @Override protected void OnDestroy () {//Destroy thread Isstop = true;
 Super.ondestroy ();
  private void Initview () {Viewpager = (Viewpager) Findviewbyid (R.id.viewpager); LldotGroup = (linearlayout) Findviewbyid (R.id.ll_dot_group);

  Tvbannertextdesc = (TextView) Findviewbyid (R.ID.TV_BANNER_TEXT_DESC);
  Imageviewcontainer = new arraylist<imageview> (); 
  int[] Imageids = new int[] {r.drawable.a, r.drawable.b, r.drawable.c, R.DRAWABLE.D, R.DRAWABLE.E,

  };
  ImageView ImageView = null;
  View dot = null;
  Layoutparams params = null;
   for (int id:imageids) {ImageView = new ImageView (this);
   Imageview.setbackgroundresource (ID);

   Imageviewcontainer.add (ImageView);
   Add a dot to the line layout once per loop dot = new View (this);
   Dot.setbackgroundresource (R.drawable.dot_bg_selector);
   params = new Layoutparams (5, 5);
   Params.leftmargin = 10;
   Dot.setenabled (FALSE);
   Dot.setlayoutparams (params); Lldotgroup.addview (dot);
  Add "point"} Viewpager.setadapter to the linear layout (new Banneradapter ());

  Viewpager.setonpagechangelistener (New Bannerpagechangelistener ());
 Select the first picture, text description Tvbannertextdesc.settext (bannertextdescarray[0]); Lldotgroup.getchildat (0). SetEnabled (True);
 Viewpager.setcurrentitem (0); /** * Viewpager Adapter/Private class Banneradapter extends Pageradapter {@Override public void Destroyitem ( ViewGroup container, int position, object object) {Container.removeview imageviewcontainer.get (position% Imageviewcon
  Tainer.size ())); @Override public Object Instantiateitem (viewgroup container, int position) {View view = Imageviewcontainer.get (

   Position% imageviewcontainer.size ()); 
     Add Click event View.setonclicklistener for each page (new View.onclicklistener () {@Override public void OnClick (view v) {
    Toast.maketext (Mainactivity.this, "Page was clicked", Toast.length_short). Show ();

   }

   });
   Container.addview (view);
  return view;
  @Override public int GetCount () {return integer.max_value;
  @Override public boolean isviewfromobject (view view, Object object) {return view = = object; }/** * Banner page switch listener/private class BaNnerpagechangelistener implements Viewpager.onpagechangelistener {@Override public void onpagescrollstatechanged (int  ARG0) {//Nothing Todo} @Override public void onpagescrolled (int arg0, float arg1, int arg2) {//Nothing  To do} @Override the public void onpageselected (int position) {//After the remainder of the index, get the new page's index int newpositon = position
   % imageviewcontainer.size ();
   Sets the description of the picture according to the index Tvbannertextdesc.settext (Bannertextdescarray[newpositon]);
   Sets the previous point to be selected Lldotgroup.getchildat (predotposition). SetEnabled (false);
   The point is selected according to the index Lldotgroup.getchildat (Newpositon). SetEnabled (True);
  The position of the new index assigned to the previous index predotposition = Newpositon;

 }

 }

}

Reference sources
http://blog.csdn.net/allen315410/article/details/39294343
Https://github.com/331637495/BannerDemo

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.