Android Viewpager realize picture carousel effect _android

Source: Internet
Author: User
Tags object object prepare

In the app picture's carousel display can say is the very common realization effect, its realization principle is only utilizes the Viewpager, then uses the handler each time to set the Viewpager CurrentItem to the current item position+1 can. Let's take a look at the effect chart first:

is to achieve the effect of such a carousel ad.

Because this is their own in order to practice imitation of a tourist app do, so the data here is to use grasping bag tools to crawl, prepare data and other work is not here to repeat, anyway, the addition of data is generally the same. My idea is to get the data from the network in real time (you can also write the data dead), and then through the Network tool class and JSON parsing class to complete the parsing and encapsulation of the data from the list collection. Determines how many page pages the Viewpager has, depending on the length of the collection, and how many dots are below. In the function, you first set a Boolean-type flag bit to determine whether to stop the carousel (we want to end the carousel when this page is not visible (OnStop ()), and define a global variable to record the position of the current small dot.
Private Boolean isstop = false; Flag bit to determine whether to stop the carousel
private int previouspointenale = 0; Mark the position of the last small dot

Then we have to prepare for the Viewpager, for example, dynamically based on data entries to generate small dots, define adapters, and so on, the code is as follows:

/** * Banner's picture Carousel event initialization/private void Initcycleevent () {/////////* Initialize small dots based on the number of images resolved Linearlayout.layoutparams
    Params
      for (int i = 0; i < imageviewlist.size (); i++) {View dot = new View (getactivity ()); 
      Dot.setbackgroundresource (R.drawable.point_background);
      params = new Linearlayout.layoutparams (15, 15);
      Params.leftmargin = 10;
      Dot.setlayoutparams (params);
      Dot.setenabled (FALSE);
    Ll_dot_group.addview (dot); //define Anonymous Adapter adapter = new Pageradapter () {@Override public int getcount () {//Because the carousel is implemented, the value is set to
      Put the big some return integer.max_value;
      @Override public boolean isviewfromobject (view view, Object object) {return view = = object; @Override public Object Instantiateitem (ViewGroup container, final int position) {IMAGEVIEWLIST.G
         ET (position% imageviewlist.size ()). Setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {Intent Intent = new Intent (getactivity (), webviewactivity.class);
            Intent.putextra ("url", bannerlist.get (position% imageviewlist.size ()). GETURL ());
          StartActivity (Intent);
        }
        });
        Container.addview (imageviewlist.get (position% imageviewlist.size ()));
      Return Imageviewlist.get (position% imageviewlist.size ()); @Override public void Destroyitem (ViewGroup container, int position, object object) {Container.rem
      Oveview (imageviewlist.get (position% imageviewlist.size ()));
    }
    };
    Vp_banner.setadapter (adapter);
    Initializes the first page page and the first small dot vp_banner.setcurrentitem (0);
    Ll_dot_group.getchildat (0). SetEnabled (True);
  Set up the listening Vp_banner.addonpagechangelistener for Viewpager (New Mypagechangelistener ());
 }

Here dot dots We didn't use the picture, but the custom <selector> and <shape> combined to show it.

<?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 android:drawable= "@drawable/point_bg_normal" android:state_enabled= "false"/>

</selector>

When the dot gets the focus, it shows this <shape> resource file:

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

  <corners android:radius=" 3DP "/> <solid android:color=

  " # Aaffffff "/>

</shape>

When the focus is lost:

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

  <corners android:radius=" 3DP "/> <solid android:color=

  " # 55000000 "/>

</shape>

The GetCount () method in adapter Pageradapter, which returns the number of page pages for the generated Viewpager, the Instantiateitem () method (Load page) is executed according to GetCount () , so we're going to have to "infinite" loops here, so we set it larger and use the maximum value of the Integer.max integer to represent it. Imageviewlist is the collection that stores the ImageView we want to show, and when we normally don't need a carousel, we directly addview () according to position, but because to achieve the carousel, So we use the position and the length of the imageviewlist set to determine the subscript for the picture.

Position% imageviewlist.size ()

The following is the code that defines the dots for the adapter and the dynamic generation of the location of the picture:

/** * Banner's picture Carousel event initialization/private void Initcycleevent () {/////////* Initialize small dots based on the number of images resolved Linearlayout.layoutparams
    Params
      for (int i = 0; i < imageviewlist.size (); i++) {View dot = new View (getactivity ());
      Dot.setbackgroundresource (R.drawable.point_background);
      params = new Linearlayout.layoutparams (15, 15);
      Params.leftmargin = 10;
      Dot.setlayoutparams (params);
      Dot.setenabled (FALSE);
    Ll_dot_group.addview (dot); //define Anonymous Adapter adapter = new Pageradapter () {@Override public int getcount () {//Because the carousel is implemented, the value is set to
      Put the big some return integer.max_value;
      @Override public boolean isviewfromobject (view view, Object object) {return view = = object; @Override public Object Instantiateitem (ViewGroup container, final int position) {IMAGEVIEWLIST.G
          ET (position% imageviewlist.size ()). Setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View v) {Intent Intent = new Intent (getactivity (), webviewactivity.class);
            Intent.putextra ("url", bannerlist.get (position% imageviewlist.size ()). GETURL ());
          StartActivity (Intent);
        }
        });
        Container.addview (imageviewlist.get (position% imageviewlist.size ()));
      Return Imageviewlist.get (position% imageviewlist.size ()); @Override public void Destroyitem (ViewGroup container, int position, object object) {Container.rem
      Oveview (imageviewlist.get (position% imageviewlist.size ()));
    }
    };
    Vp_banner.setadapter (adapter);
    Initializes the first page page and the first small dot vp_banner.setcurrentitem (0);
    Ll_dot_group.getchildat (0). SetEnabled (True);
  Set up the listening Vp_banner.addonpagechangelistener for Viewpager (New Mypagechangelistener ());

 }

Remember that the AddView () and Removeview () are all based on the value of the remainder to find the corresponding location of the ImageView should be displayed. Initialization work done, the following should be completed on the carousel operation, where we open a thread every time, to get the current Viewpager page position, then +1, and then set the current page subscript for this new value can:

/**
   * The method to open a carousel thread/
  private void Startbannerscrollthread () {new Thread () {new
    Runnable () {
      @Override Public
      void Run () {
        ///first determines whether to stop the carousel while
        (!isstop) {
          systemclock.sleep);
          Handler.post (New Runnable () {
            @Override public
            void Run () {
              int newindex = Vp_banner.getcurrentitem () + 1 ;
              Vp_banner.setcurrentitem (NewIndex);}})
    . Start ();
  }

Of course, because each picture is shown to us, the indicative dots at the bottom of the picture have to change accordingly, so in the viewpager we have to deal with its sliding events, so we customize a class, Implements the Viewpager.onpagechangelistener interface and handles the corresponding events in the Onpageselected () method:

   /**
* Viewpager Sliding Monitor Event * *
  class Mypagechangelistener implements Viewpager.onpagechangelistener {

    @ Override public
    void onpagescrolled (int position, float positionoffset, int positionoffsetpixels) {

    }

    @ Override public
    void onpageselected (int position) {
      //Get a new page position
      int newposition = position% Imageviewlist.size ();
      Sets the background of the last small dot to the default that
      Ll_dot_group.getchildat (Previouspointenale). SetEnabled (false);
      Sets the dot style
      Ll_dot_group.getchildat (newposition). SetEnabled (True) of the current page page;
      Assign the new position to Previouspointenale
      Previouspointenale = newposition;
    }

    @Override public
    void onpagescrollstatechanged (int state) {

    }
  }

The key code and thinking is like this, here is another article I refer to, write well, the following link here:

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.