Android Perfect for smooth transition Viewpager banner _android

Source: Internet
Author: User
Tags object object

We often see the banner interface of some apps that can loop through multiple ad images and manually slide loops. See that effect, I believe everyone will think of Viewpager, but Viewpager does not support the circular page, so to realize the cycle still need to do their own. Finally, there is the question of how to smooth the transition to the first page to the last one. It all stems from someone DMS asked me how to smooth the transition of Viewpager banner, for this problem, I think to realize and share the next, this article is to solve these problems and write.

1. Initialize the layout

Let's start by writing a Viewpager ad bar 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/vp" Android: Layout_width= "Match_parent" android:layout_height= "210DP"/> <linearlayout android:layout_width= "Match_" Parent "android:layout_height=" wrap_content "android:layout_alignbottom=" "@id/vp" android:background= "#55000000" an Droid:gravity= "Center_horizontal" android:orientation= "vertical" android:padding= "5DP" > <textview android:i D= "@+id/tv_img_desc" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:text= "This is advertising.
   Title "android:textcolor=" #ffffff "android:textsize=" "16sp"/> <!--dynamically add dots, using a horizontal linear layout--> <linearlayout Android:id= "@+id/ll_dot_group" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Androi d:orientation= "Horizontal"/> </linearlayOut> </RelativeLayout>

 

At this point the effect is as follows, is not already have a point appearance:

2.Activity implementation

The next step into the key implementation code, of course, the implementation of the activity is also difficult to fail us, which viewpager data, in order to facilitate, this article directly with the local data simulation. But in the actual project development data mostly comes from the network.

public class Mainactivity extends Appcompatactivity implements Viewpager.onpagechangelistener {private List<imagevi
 Ew> vplists; Private LinearLayout Ll_dot_group;
 Used to add small dots private string[] imagedescarrs;
 Private TextView Tv_img_desc;

 Private Viewpager VP; Private Boolean isswitchpager = false; Default does not toggle private int previousposition = 0; Default is 0 private Handler Handler = new Handler () {public void Handlemessage (Android.os.Message msg) {//update current ViewPage
  R's current entry to display Vp.setcurrentitem (Vp.getcurrentitem () + 1);

 }
 };
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
  Setcontentview (R.layout.activity_main);
 Initview ();
  /** * Initialize view/private void Initview () {VP = (Viewpager) Findviewbyid (R.ID.VP);
  Ll_dot_group = (linearlayout) Findviewbyid (R.id.ll_dot_group);

  Tv_img_desc = (TextView) Findviewbyid (R.ID.TV_IMG_DESC);
  Initviewpagerdata ();

  Vp.setadapter (New Viewpageradapter ()); Set Current VieWpager to display the first few entries int item = INTEGER.MAX_VALUE/2-(integer.max_value/2% vplists.size ());

  Vp.setcurrentitem (item);
  Set the first dot to white to display the first TextView content Ll_dot_group.getchildat (previousposition). SetEnabled (True);
  Tv_img_desc.settext (Imagedescarrs[previousposition]);

  Set the Viewpager sliding Monitor event Vp.addonpagechangelistener (this);
     Implements the automatic switching function new Thread () {public void run () {while (!isswitchpager) {systemclock.sleep (3000);
    Take the handler message we created Handler.sendemptymessage (0);
 }}.start (); /** * Initialize Viewpager data/private void Initviewpagerdata () {imagedescarrs = new string[]{"Heading 1", "Heading 2", "Heading 3", "
  Heading 4 ", Title 5"};
  vplists = new arraylist<imageview> ();
  int imgids[] = {r.drawable.a, r.drawable.b, r.drawable.c, R.DRAWABLE.D, R.DRAWABLE.E};
  ImageView IV;

  View Dotview;
   for (int i = 0; i < imgids.length. i++) {IV = new ImageView (this);
   Iv.setbackgroundresource (Imgids[i]);
   Vplists.add (iv); Preparing data for small dots Dotview = NEW View (Getapplicationcontext ());
   Dotview.setbackgroundresource (R.drawable.selector_dot);
   Set small dot width and height layoutparams params = new Layoutparams (15, 15);
   Sets the distance between each small dot if (i!= 0) {params.leftmargin = 15;
   } dotview.setlayoutparams (params);
   Set small dot default state dotview.setenabled (FALSE);
  Adding Dotview to the linear layout of Ll_dot_group.addview (Dotview);
   }/** * Define data Adapter/Private class Viewpageradapter extends Pageradapter {@Override public int getcount () {
  return integer.max_value;
  //whether to reuse the current View object @Override public boolean isviewfromobject (view arg0, Object arg1) {return arg0 = = Arg1; //Initialize the content to be displayed for each entry @Override public Object instantiateitem (viewgroup container, int position) {//Hold position location%
   The set. size int newposition = position% vplists.size ();
   Gets the content to display for the entry ImageView ImageView IV = Vplists.get (newposition);
   To add IV to the container Container.addview (iv);
  return IV; }//Destroy entry @Override public void Destroyitem (ViewGroup container, int position, object object) {//Remove entry Container.removeview (View Object);  When the new page is selected, call @Override public void onpageselected (int position) {//hold the position location% collection. size int newposition
  = position% vplists.size ();
  The small dot to remove the postion position is set to True Ll_dot_group.getchildat (newposition). SetEnabled (True);
  Set a small dot to false Ll_dot_group.getchildat (previousposition). SetEnabled (false);
  Tv_img_desc.settext (Imagedescarrs[newposition]);
 Previousposition = newposition;
  @Override protected void OnDestroy () {//When the activity is destroyed, place the toggle mark to True Isswitchpager = true;
 Super.ondestroy ();  @Override public void onpagescrollstatechanged (int state) {}//When the page starts sliding @Override public void onpagescrolled (int

 Position, float positionoffset, int positionoffsetpixels) {}}

As we have solved the problem of smooth transition, the key is Viewpageradapter:

GetCount method we return to Integer.max_value

public int GetCount () {return
 integer.max_value;
}

To initialize the content to be displayed for each entry, we hold the position position% collection. Size

@Override public
Object instantiateitem (viewgroup container, int position) {
 //Hold position location% collection. Size
 int newposition = position% vplists.size ();
 Gets the content to display for the entry ImageView
 ImageView IV = Vplists.get (newposition);
 To add IV to the container
 Container.addview (iv);
 Return IV
}

At this point we found that the last ad can be a smooth transition, but there is another question, that from the first, we go to the left? In fact, it is easy to solve, is to set the first entry for the integer.max_value of the middle position on it, we came to the Initview method, set the current Viewpager to display the first few entries:

int item = INTEGER.MAX_VALUE/2-(integer.max_value/2% vplists.size ());
Vp.setcurrentitem (item);

The problem is solved perfectly.

The used shape related resources are as follows:

Selector_dot.xml

<?xml version= "1.0" encoding= "Utf-8"?> <selector xmlns:android=
"http://schemas.android.com/apk/res/" Android >
 <item android:drawable= "@drawable/dot_enable" android:state_enabled= "true" ></item>
 <item android:drawable= "@drawable/dot_normal" android:state_enabled= "false" ></item>
</ Selector>

Dot_enable.xml

<?xml version= "1.0" encoding= "Utf-8"?> <shape xmlns:android=
"http://schemas.android.com/apk/res/" Android ">
 <corners android:radius=" 5DP "/>
 <solid android:color=" @android: Color/white "/>
</shape>

Dot_normal.xml

<?xml version= "1.0" encoding= "Utf-8"?> <shape xmlns:android=
"http://schemas.android.com/apk/res/" Android ">
 <corners android:radius=" 5DP "/>
 <solid android:color=" @android: Color/darker_gray "/ >
</shape>

Look at the effect chart:

To this, a smooth transition of the Viewpager advertising bar has been perfectly implemented.

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.