Android Sliding Menu Frame complete parsing, teach you how to implement sliding menu effects in one minute

Source: Internet
Author: User
Tags integer reset sleep valid

Before I told you about the history of the simplest way to implement the sliding menu, I believe we all remember. If you forget the implementation of the principle or have not seen the friends, please go to see the previous article Android sliding menu effects, imitation of the client side sideslip effect, the history of the most simple sideslip, because we want to implement the sliding menu framework is based on the same principle.

In the end, it was mentioned in the last article that if you have a lot of activity in your application that needs to be added to the sliding menu, then the code of hundreds of lines will be required for each event to work, and a simple slide menu implementation is useless. So we're going to implement a sliding menu frame today, and then we can introduce the sliding menu function in any activity in one minute.

First, let's talk about the principle of implementation. Say is the frame of the sliding menu, in fact, it is also very simple, that is, we customize a layout, in this custom layout to achieve a good sliding menu function, and then as long as the activity in the layout of the file to introduce our custom layout, the activity has a sliding menu function. The principle is finished, is it very simple? Let's get it done now.

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

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

public class Slidinglayout extends LinearLayout implements Ontouchlistener {/** * scroll to show and hide the left layout when the finger slides need 
     Reach the speed.  
      
    * * public static final int snap_velocity = 200; 
     /** * Screen width value.  
      
    * * private int screenwidth; /** * The left side of the layout can slide up to the left edge. 
     The value is determined by the width of the left layout, and marginleft can no longer be reduced after it reaches this value.  
      
    * * private int leftedge; /** * The left side of the layout can slide up to the right edge. 
     The value of 0, that is, MarginLeft reached 0, can not increase.  
      
    * Private int rightedge = 0; 
     /** * When the left layout is fully displayed, leave the width value of the right layout.  
      
    * Private int leftlayoutpadding = 80; 
     /** * 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; /** * The left layout is currently displayed or hidden. 
     This value is changed only when it is fully displayed or hidden, and this value is not valid during sliding.  
      
    * * Private Boolean isleftlayoutvisible; 
     /** * Left Layout object.  
      
    * * Private View leftlayout; 
    /** * Right Layout object.  
      
    * * Private View rightlayout; 
     /** * Used to monitor view of sideslip events.  
      
    * * Private View Mbindview; 
     /** * parameter to the left layout, which is used to redefine the width of the left layout and to change the value of the LeftMargin.  
      
    * * Private marginlayoutparams leftlayoutparams; 
     /** * The parameter of the right layout, which is used to redefine the width of the right layout.  
      
    * * Private marginlayoutparams rightlayoutparams; 
     /** * is used to calculate the speed at which fingers are sliding.  
      
    * * Private Velocitytracker Mvelocitytracker; 
     /** * Overrides the Slidinglayout constructor, which gets the width of the screen.  
        * * @param context * @param attrs/Public slidinglayout (context, AttributeSet attrs) {  
        Super (context, attrs);  
        WindowManager wm = (WindowManager) context.getsystemservice (Context.window_service);  
    ScreenWidth = Wm.getdefaultdisplay (). GetWidth (); 
     /** * Binds the view that listens for sideslip events, that is, sliding in the bound view to show and hide the left layout. 
     * * @param BindView * needs to bind to the View object. */public void SetscroLlevent (View bindview) {mbindview = BindView;  
    Mbindview.setontouchlistener (this); 
     /** * Scrolls the screen to the left layout interface with the scrolling speed set to 30.  
    */public void Scrolltoleftlayout () {new Scrolltask (). Execute (30); 
     /** * Scrolls the screen to the right layout interface with the scrolling speed set to-30.  
    */public void Scrolltorightlayout () {new Scrolltask (). Execute (-30); 
     /** * The left layout is fully displayed or completely hidden, and this value is not valid during sliding. 
     * * @return Left layout full display returns True, full hide returns false.  
    * * Public boolean isleftlayoutvisible () {return isleftlayoutvisible; 
     /** * Reset the parameters of the left and right layouts in the onlayout. */@Override protected void OnLayout (Boolean changed, int l, int t, int r, int b) {super.onlayout (Chang  
        Ed, L, T, R, b);  
            if (changed) {//Get left Layout object leftlayout = Getchildat (0);  
            Leftlayoutparams = (marginlayoutparams) leftlayout.getlayoutparams (); //Reset the width of the left layout object to screen width minus leftlayoutpadding leftlayoutparams.width = screenwidth-leftlayoutpadding;  
            Sets the width of the left layout with a negative left margin of Leftedge =-leftlayoutparams.width;  
            Leftlayoutparams.leftmargin = Leftedge;  
            Leftlayout.setlayoutparams (Leftlayoutparams);  
            Gets the right layout object rightlayout = Getchildat (1);  
            Rightlayoutparams = (marginlayoutparams) rightlayout.getlayoutparams ();  
            Rightlayoutparams.width = ScreenWidth;  
        Rightlayout.setlayoutparams (Rightlayoutparams); @Override public boolean Ontouch (View V, motionevent event) {Createvelocitytracker (E)  
        VENT); 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 the horizontal axis, calculate the moving distance, to adjust the left layout of the LeftMargin value, so as to show and hide the LeftLayout xmove = Event.getrawx ();  
            int Distancex = (int) (xmove-xdown);  
            if (isleftlayoutvisible) {leftlayoutparams.leftmargin = Distancex;  
            else {leftlayoutparams.leftmargin = Leftedge + Distancex;   
            } if (Leftlayoutparams.leftmargin < Leftedge) {leftlayoutparams.leftmargin = Leftedge; else if (Leftlayoutparams.leftmargin > Rightedge) {leftlayoutparams.leftmargin = Ri  
            Ghtedge;  
            } leftlayout.setlayoutparams (Leftlayoutparams);  
        Break Case MOTIONEVENT.ACTION_UP://When the finger is raised, determine 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 (Wanttoshowleftlayout ()) {if (Shouldscrolltoleftlayout ()) {Scrolltoleftlayout  
                ();  else {scrolltorightlayout ();
                } else if (Wanttoshowrightlayout ()) {if (Shouldscrolltocontent ()) {  
                Scrolltorightlayout ();  
                else {scrolltoleftlayout ();  
            } recyclevelocitytracker ();  
        Break  
    return Isbindbasiclayout (); /** * Determines whether the current gesture is intended to display the right layout. 
     If the distance between the fingers is negative and the current left layout is visible, the current gesture is considered to show the right layout. 
     * * @return Current gesture to display the right layout returns TRUE, otherwise returns false.  
    * Private Boolean Wanttoshowrightlayout () {return Xup-xdown < 0 && isleftlayoutvisible; /** * Determines whether the current gesture is intended to display the left layout. 
     If the distance between the fingers is positive and the current left layout is not visible, the current gesture is considered to show the left layout. 
     * * @return Current gesture to display the left layout returns true, otherwise returns false.  
    * Private Boolean Wanttoshowleftlayout () {return xup-xdown > 0 &&!isleftlayoutvisible; /** * Determine if scrolling should be done to show the left layout. If the finger moves more than 1/2 of the screen, orThe finger moves faster than snap_velocity, * think it should be scrolling to show the left layout. 
     * * @return return FALSE If you should scroll to show the left layout to return true. * Private Boolean Shouldscrolltoleftlayout () {return xup-xdown > SCREENWIDTH/2 | | getscrollvelocity  
    () > Snap_velocity; /** * Determine if scrolling should be done to show the right layout. 
     If the finger moves at a distance plus leftlayoutpadding greater than 1/2 of the screen, * or the finger moves faster than the snap_velocity, think it should scroll to show the right layout. 
     * * @return returns FALSE if you should scroll to show the right layout to return true.
                * Private Boolean shouldscrolltocontent () {return xdown-xup + leftlayoutpadding > SCREENWIDTH/2 ||  
    Getscrollvelocity () > snap_velocity; 
     /** * Determines whether the view of the binding sliding event is a base layout, does not support custom layout, supports only four basic layout, * absolutelayout has been deprecated.  
     * * @return If the view of the bound sliding event is linearlayout,relativelayout,framelayout, the * Tablelayout returns TRUE, otherwise it returns false.  
 * * Private Boolean isbindbasiclayout () {if (Mbindview = = null) {return false;       String viewName = Mbindview.getclass (). GetName (); Return Viewname.equals (LinearLayout.class.getName ()) | | Viewname.equals (RelativeLayout.class.getName ()) | | Viewname.equals (FrameLayout.class.getName ()) | |  

    Viewname.equals (TableLayout.class.getName ()); 
     /** * 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, the number of pixels moved per second in units.  
        * * 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; Class Scrolltask extends Asynctask<integer, Integer, integer> {@Override PR  
            otected integer doinbackground (integer ... speed) {int leftMargin = Leftlayoutparams.leftmargin;  
            Scrolls the interface according to the incoming speed, and jumps out of the loop when the scroll reaches the left or right edge.  
                while (true) {LeftMargin = LeftMargin + speed[0];  
                    if (LeftMargin > Rightedge) {leftMargin = Rightedge;  
                Break  
                    } if (LeftMargin < Leftedge) {leftMargin = Leftedge;  
                Break  
                } publishprogress (LeftMargin); 

 
                In order for the scrolling effect to occur, each loop causes the thread to sleep for 20 milliseconds, so the naked eye can see the scrolling animation.  
Sleep (20);            } if (Speed[0] > 0) {isleftlayoutvisible = true;  
            else {isleftlayoutvisible = false;  
        return leftMargin; } @Override protected void Onprogressupdate (Integer ... leftMargin) {Leftlayoutpara  
            Ms.leftmargin = leftmargin[0];  
        Leftlayout.setlayoutparams (Leftlayoutparams); } @Override protected void OnPostExecute (Integer leftMargin) {Leftlayoutparams.lef  
            Tmargin = LeftMargin;  
        Leftlayout.setlayoutparams (Leftlayoutparams); 
     }/** * 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.