Android implementation of the picture scrolling control, including the page sign function, let your application like Taobao dazzle up

Source: Internet
Author: User
Tags abs integer sleep thread

First off, this morning, when I get up, my hand slipped out of my mobile phone, the result of my 2.5 Motorola milestone generation so rest, so I decided today to anger more, to commemorate my dead love machine.

If you are the net buys the person, your handset must not have Taobao client. Attention to special effects people will find that Taobao, whether it is a website or a mobile phone client, the home page will have a picture scrolling player, showing some of its recommended products. This can almost use Amoy name of the function, looks still very cool, we will come to realize today.

Implementation of the principle is actually still before that article Android sliding menu effects, imitation of the client side sideslip effect, the history of the most simple sideslip implementation, is based on that principle of another variant. Is the so-called Itong, really mastered a method, you can use this method to transform a variety of different effects.

Today still implements a custom control, and then we can implement the effect of the picture scroll by referencing it in the layout file of any activity.

To create a new Android project in Eclipse, the project name is called Slidingviewswitcher.

Create a new class named Slidingswitcherview, which inherits from Relativelayout and implements the Ontouchlistener interface, which is as follows:

public class Slidingswitcherview extends Relativelayout implements Ontouchlistener {/** * Let the menu roll and the fingers slide 
     The speed to be achieved.  
      
    * * public static final int snap_velocity = 200; 
     Width of/** * slidingswitcherview.  
      
    * * private int switcherviewwidth; 
     /** * Subscript for the element currently displayed.  
      
    * * private int currentitemindex; 
     The total number of elements contained in the/** * menu.  
      
    * * private int itemscount; 
     /** * The offset boundary value of each element.  
      
    * Private int[] borders; /** * can slide up to the left edge. 
     The value is determined by the total number of elements contained in the menu, and marginleft cannot be reduced after it reaches this value.  
      
    * */private int leftedge = 0; /** * can slide up to the right edge. 
     The value is constant 0,marginleft This value cannot be increased.  
      
    * Private int rightedge = 0; 
     /** * Record the horizontal axis when the finger is pressed.  
      
    * * Private float Xdown; 
     /** * Records the horizontal axis when the finger moves.  
      
    * * Private float xmove; 
     /** * Record the horizontal axis when the mobile phone is raised.  
      
    * * Private float xup; 
     /** * Menu layout. * * PRIvate LinearLayout itemslayout; 
     /** * Label layout.  
      
    * * Private linearlayout dotslayout; 
     The first element in the/** * menu.  
      
    * * Private View FirstItem; 
     The layout of the first element in the/** * menu to change the value of the LeftMargin to determine which element is currently displayed.  
      
    * * Private marginlayoutparams firstitemparams; 
     /** * is used to calculate the speed at which fingers are sliding.  
      
    * * Private Velocitytracker Mvelocitytracker; 
     /** * Overrides the Slidingswitcherview constructor, which allows you to reference the current custom layout in XML. * * @param context * @param attrs/public Slidingswitcherview, AttributeSet attrs  
    ) {Super (context, attrs); 
     /** * Scrolls to the next element.  
    */public void Scrolltonext () {new Scrolltask (). Execute (-20); 
     /** * Scrolls to the previous element.  
    */public void scrolltoprevious () {new Scrolltask (). Execute (20); 
     /** * Reset the parameters of menu elements and label elements in OnLayout. * * @Override protected void OnLAyout (Boolean changed, int l, int t, int r, int b) {super.onlayout (changed, L, T, R, b);  
            if (changed) {Initializeitems ();  
        Initializedots (); 
     }/** * Initializes the menu element, increases the listener event for each child element, and changes the width of all child elements so that they are equal to the width of the parent element.  
        * * private void Initializeitems () {switcherviewwidth = GetWidth ();  
        Itemslayout = (linearlayout) getchildat (0);  
        Itemscount = Itemslayout.getchildcount ();  
        Borders = new Int[itemscount];  
            for (int i = 0; i < Itemscount i++) {Borders[i] =-I * switcherviewwidth;  
            View item = Itemslayout.getchildat (i);  
            Marginlayoutparams params = (marginlayoutparams) item.getlayoutparams ();  
            Params.width = Switcherviewwidth;  
            Item.setlayoutparams (params);  
        Item.setontouchlistener (this);  
        } Leftedge = borders[itemscount-1]; FirstItem = Itemslayout.getchildat(0);  
    Firstitemparams = (marginlayoutparams) firstitem.getlayoutparams (); 
     /** * initializes the label element.  
        * * private void Initializedots () {dotslayout = (linearlayout) getchildat (1);  
    Refreshdotslayout ();  
        @Override public boolean Ontouch (View V, motionevent event) {Createvelocitytracker (event);  
            Switch (event.getaction ()) {case Motionevent.action_down://When the finger is pressed, record the horizontal axis when pressed  
            Xdown = Event.getrawx ();  
        Break Case Motionevent.action_move://When the fingers move, contrast to the horizontal axis, calculate the moving distance, to adjust the left layout of the LeftMargin value, so as to show and hide the left layout Xmov  
            E = Event.getrawx ();  
            int Distancex = (int) (Xmove-xdown)-(Currentitemindex * switcherviewwidth);  
            Firstitemparams.leftmargin = Distancex;  
            if (Beabletoscroll ()) {firstitem.setlayoutparams (firstitemparams);  
       } break; Case MOTIONEVENT.ACTION_UP://When the finger is raised, make a judgment on the intention of the current gesture, and decide whether to scroll to the left layout or to scroll to the right layout Xup = event.getrawx  
            (); if (Beabletoscroll ()) {if (wantscrolltoprevious ()) {if (shouldscrolltoprevious ())  
                        ) {currentitemindex--;  
                        Scrolltoprevious ();  
                    Refreshdotslayout ();  
                    else {scrolltonext ();  
                        } else if (Wantscrolltonext ()) {if (Shouldscrolltonext ()) {  
                        currentitemindex++;  
                        Scrolltonext ();  
                    Refreshdotslayout ();  
                    else {scrolltoprevious ();  
            }} recyclevelocitytracker ();  
        Break  
    return false; 
  }  
      
    /**   * is currently able to scroll, scrolling to the first or last element will no longer scroll. 
     * * @return The current LeftMargin value returns true between Leftedge and Rightedge, or false. * Private Boolean Beabletoscroll () {return Firstitemparams.leftmargin < Rightedge && Firstitemp  
    Arams.leftmargin > Leftedge; /** * Determines whether the current gesture is intended to scroll to the previous menu element. 
     If the finger moves at a positive distance, the current gesture is considered to be scrolling to the previous menu element. 
     * * @return The current gesture wants to scroll to the previous menu element to return True, otherwise return false.  
    * Private Boolean wantscrolltoprevious () {return xup-xdown > 0; /** * Determines whether the current gesture is intended to scroll to the next menu element. 
     If the finger moves at a negative distance, the current gesture is considered to be scrolling to the next menu element. 
     * * @return The current gesture wants to scroll to the next menu element to return True, otherwise return false.  
    * Private Boolean Wantscrolltonext () {return Xup-xdown < 0; /** * Determines whether the next menu element should be scrolled. 
     If the finger moves at a distance greater than 1/2 of the screen, or the finger moves faster than snap_velocity, * it should be scrolled to the next menu element. 
     * * @return returns FALSE if you should scroll to the next menu element to return True. * Private Boolean Shouldscrolltonext () {return xDown-xup > SWITCHERVIEWWIDTH/2 | |  
    Getscrollvelocity () > snap_velocity; /** * Determines whether the previous menu element should be scrolled. 
     If the finger moves more than 1/2 of the screen, or the finger moves faster than snap_velocity, * it should be scrolled to the previous menu element. 
     * * @return returns FALSE if you should scroll to the previous menu element to return True. * Private Boolean shouldscrolltoprevious () {return xup-xdown > SWITCHERVIEWWIDTH/2 | | getscrollvelo  
    City () > snap_velocity; 
     /** * Refresh the Label element layout and refresh every time the Currentitemindex value changes.  
        * * private void Refreshdotslayout () {dotslayout.removeallviews (); for (int i = 0; i < Itemscount i++) {linearlayout.layoutparams linearparams = new LINEARLAYOUT.LAYOUTPA  
            Rams (0, layoutparams.fill_parent);  
            Linearparams.weight = 1;  
            Relativelayout relativelayout = new Relativelayout (GetContext ());  
            ImageView image = New ImageView (GetContext ());  
        if (i = = Currentitemindex) {        Image.setbackgroundresource (r.drawable.dot_selected);  
            else {image.setbackgroundresource (r.drawable.dot_unselected); } relativelayout.layoutparams relativeparams = new Relativelayout.layoutparams (Layout  
            Params.wrap_content, layoutparams.wrap_content);  
            Relativeparams.addrule (relativelayout.center_in_parent);  
            Relativelayout.addview (image, Relativeparams);  
        Dotslayout.addview (Relativelayout, linearparams); 
     }/** * Creates the Velocitytracker object and joins the touch event into the velocitytracker. * * @param event * Right layout listener control sliding event/private void Createvelocitytracker (Motionevent event  
        {if (Mvelocitytracker = = null) {Mvelocitytracker = Velocitytracker.obtain ();  
    } mvelocitytracker.addmovement (event); 
     /** * Gets the sliding speed of the finger on the monitor view of the right layout. *  
     * @Return sliding speed, in units of the number of pixels moved per second.  
        * * Private int getscrollvelocity () {mvelocitytracker.computecurrentvelocity (1000);  
        int velocity = (int) mvelocitytracker.getxvelocity ();  
    return math.abs (velocity); 
     /** * Reclaims Velocitytracker objects.  
        * * private void Recyclevelocitytracker () {mvelocitytracker.recycle ();  
    Mvelocitytracker = null; 
     When/** * Detects menu scrolling, the values that traverse border,border are stored in {@link #borders}. * * @param leftMargin * The left offset value of the first element * @param speed * Scrolling speed, positive note scrolling to the right, negative description scroll left 
     。 
     * @return through any one border returns True, otherwise returns false. * * Private Boolean iscrossborder (int leftMargin, int speed) {for (int border:borders) {if (Speed > 0) {if (leftMargin >= border && leftmargin-speed < border) {return  
                True  
         }} else {       if (leftMargin <= border && leftmargin-speed > Border) {return true;  
    }} return false; 
     /** * Finds a border value closest to the current leftmargin. 
     * * @param leftMargin * The left offset value of the first element * @return The nearest border value from the current leftMargin.  
        * * Private int findclosestborder (int leftMargin) {int absleftmargin = Math.Abs (LeftMargin);  
        int closestborder = borders[0];  
        int closestmargin = Math.Abs (Math.Abs (Closestborder)-absleftmargin);  
            for (int border:borders) {int margin = Math.Abs (math.abs (border)-absleftmargin);  
                if (Margin < Closestmargin) {closestborder = border;  
            Closestmargin = margin;  
    } return Closestborder;  
      
    Class Scrolltask extends Asynctask<integer, Integer, integer> {    @Override protected integer doinbackground (integer ... speed) {int leftMargin = Firstitemparams.  
            LeftMargin;  
            Roll the interface according to the incoming speed, and when scrolling through the border, jump out of the loop.  
                while (true) {LeftMargin = LeftMargin + speed[0];  
                    if (Iscrossborder (LeftMargin, speed[0])) {LeftMargin = Findclosestborder (LeftMargin);  
                Break  
                } publishprogress (LeftMargin); 

 
                In order for the scrolling effect to occur, each loop causes the thread to sleep for 10 milliseconds, so the naked eye can see the scrolling animation.  
            Sleep (10);  
        return leftMargin; } @Override protected void Onprogressupdate (Integer ... leftMargin) {Firstitemparam  
            S.leftmargin = leftmargin[0];  
        Firstitem.setlayoutparams (Firstitemparams); } @Override protected void OnPostExecute (Integer leftMargin) {Firstitemparams.left Margin = LeftmargiN  
        Firstitem.setlayoutparams (Firstitemparams); 
     }/** * Causes the current thread to sleep for the specified number of milliseconds.  * * @param millis * Specifies how long the current thread sleeps, in milliseconds */private void sleep (long Millis) {try  
        {Thread.Sleep (Millis);  
        catch (Interruptedexception e) {e.printstacktrace (); }  
    }  
}

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.