Customizing the Swipe menu Slidingmenu

Source: Internet
Author: User
Tags gety

It's okay. Imitate the SCDN Client Side-by-side slide effect, customized a slindingmenu, although GitHub has a fairly mature slindingmenu Open source framework, but this blog is designed to help more students understand The principle of slidingmenu, make use more handy.

1. Analysis

First of all, the implementation of the analysis,slindingmenu layout needs to have two parts, one is the layout of menus (menu) , one is the contents (content ) the layout. Two layouts are arranged horizontally, menu layout is left, content layout is right. When initialized, the menu layout is shifted to the left so that it can be completely hidden so that the content layout is fully visible in the Activity . You can then change the left offset of the menu layout by listening to the finger swipe events to control the display and hiding of the menu layout. Schematic diagram is as follows:

When the left menu is fully displayed, the following:

2. Realize

2.1, complete the main content main_content and Left_menu layout

Two layout is simple, the layout of the main content is divided into two parts: add title bar and display content, left menu is divided into three parts, the upper and lower parts use height using layout_weight = 1, Middle with linearlayout Parcel of 5 a TextView control, height use wrap_content can be.

2.2. Customize the subclass of the ViewGroup to combine the first two layouts.

1. Use the custom control in activity-main

<com.znouy.slidingmenuview.view.slidingmenuview        android:layout_width= "match_parent"        android:layout_ height= "Match_parent" >        <!--left menu        --<include layout= "@layout/left_menu"/>        <!--main Content-        <include layout= "@layout/main_content"/></com.znouy.slidingmenuview.view.slidingmenuview>

2 . Implement the onmeasure () and onlayout () methods of the custom ViewGroup

The first is onmeasure () to measure the child, provided the first to obtain two children, by rewriting the onfinishinflate() method, This method automatically callbacks when layout parsing is complete. The code is as follows:

@Overrideprotected void Onfinishinflate () {mleft_menu = Getchildat (0); mmain_content = Getchildat (1);// The left menu is accurately measured layoutparams layoutparams = Mleft_menu.getlayoutparams (); mleftmenu_width = Layoutparams.width; Super.onfinishinflate ();}

The second is to rewrite the onmeasure () method, the child component is measured separately, because the main content is filled with the screen, it is only a fuzzy measurement, that is, call the view of the measure () to be measured. For the left-hand menu, because its width is indeterminate, it is accurate to measure its width measurespec.makemeasurespec (int size, int mode) to get wide and finally call The Setmeasureddimension () method sets the measured value, noting that the value here is non-modal.

/** 2. Sub-component measurements */@Overrideprotected void onmeasure (int widthmeasurespec, int heightmeasurespec) {//main content Measurement Mmain_ Content.measure (Widthmeasurespec, heightmeasurespec);//left menu measurement-mode measurement of width-exact int leftwidthmeasurespec = Measurespec.makemeasurespec (mleftmenu_width,measurespec.exactly); Mleft_menu.measure (LeftWidthMeasureSpec, HEIGHTMEASURESPEC)///Set the measured value (without mode) setmeasureddimension (Measurespec.getsize (Widthmeasurespec), Measurespec.getsize (Heightmeasurespec));}

After the measurement is onlayout , the callback onlayout () is laid out and the child's position is determined. The core is that its children call the View 's layout (l,t,r,b) method to determine their respective positions.

/** 2. Layout of sub-components after measurements */@Overrideprotected void OnLayout (Boolean changed, int l, int t, int r, int b) {int dx = 0;//x position offset/ /OK main content location int maincontentleft = 0 + dx;int maincontenttop = 0;int maincontentright = mmain_content.getmeasuredwidth () + dx; int maincontentbottom = Mmain_content.getmeasuredheight (); Mmain_content.layout (Maincontentleft, MainContentTop, Maincontentright,maincontentbottom);//OK left menu position int leftmenuleft =-mleft_menu.getmeasuredwidth () + dx;int LeftMenuTop = 0;int leftmenuright = 0 + dx;int Leftmenubottom = Mleft_menu.getmeasuredheight (); Mleft_menu.layout (LeftMenuleft, Leftmenutop, Leftmenuright,leftmenubottom);}

2.3. Custom ViewGroup Touch Event implementation

When the touch swipe custom viewgroup, it is necessary to process the viewgroup event Distribution, we know thatViewGroup The mechanism of event distribution mainly involves three functions.

First, dispatchtouchevent() is called to determine whether to distribute the event, which is handled by default here.

        @Overridepublic boolean dispatchtouchevent (motionevent ev) {//is handled by default-will determine in its onintercepttouchevent whether to intercept the event return Super.dispatchtouchevent (EV);}

if dispatchtouchevent () processed by default, and then called onintercepttouchevent () to determine if an event is intercepted, if the true ontouchevent (), if return false or call super.onintercepttouchevent (EV) does not intercept events, the event is left to the child view dispatchtouchevent ().

        @Overridepublic boolean onintercepttouchevent (motionevent ev) {//Determines whether it is sliding horizontally or vertically, sliding the event intercept horizontally, performing its own ontouchevent, When sliding horizontally, the ScrollView can also slide,//longitudinal slide release, perform sub-container dispatchtouchevent, do not perform ontouchevent, do not slide the screen switch (ev.getaction ()) {case MotionEvent.ACTION_DOWN:downX = Ev.getx ();d owny = Ev.gety (); break;case MotionEvent.ACTION_MOVE:float MoveX = Ev.getx () ; Float Movey = Ev.gety (); float dx = movex-downx;float dy = movey-downy;if (math.abs (dx) > Math.Abs (dy)) {//cross slide intercept R Eturn true;} Break;default:break;} return super.onintercepttouchevent (EV);}

Finally, we only need to ontouchevent () the logic for handling touch events in the When we swipe the view container to not cross the border, and then release the Call GETSCROLLX () (about GETSCROLLX () usage, please refer to this blog

ANDROID&NBSP;GETSCROLLX () detailed ) and the left menu One-second width comparison is less than if its value is less than one-second of negative left menu width, the left menu is completely displayed, otherwise the main content is completely displayed. To make the process rule slide, the scroller Startscroll () method is used to implement the sliding animation. The code is as follows:

        @Overridepublic boolean ontouchevent (Motionevent event) {//Handle touch Event switch (event.getaction ()) {case Motionevent.act Ion_down:mdownx = Event.getx (); break;case MotionEvent.ACTION_MOVE:float MoveX = Event.getx ();//Get View on X-axis offset//int dx = M Ath.round (Mdownx-movex);//A negative number means that the view (canvas) int dx =-math.round (MOVEX-MDOWNX) is shifted to pan left; Gets the x-coordinate of the left edge of the screen before panning the view int scrollx = GETSCROLLX (); if (scrollx + dx <-mleft_menu.getmeasuredwidth ()) {//left border out of bounds//full display left menu s Crollto (-mleft_menu.getmeasuredwidth (), 0);} else if (scrollx + dx > 0) {//Right border out of bounds//full display of main content scrollto (0, 0);} else {//not out of bounds Scrollby (DX, 0);} Mdownx = movex;//is constantly changing the position of the press during the move break;case motionevent.action_up://get the position of the left edge of the viewgroup when the screen is released (position at the left edge of the screen) int scrollX2 = GETSCROLLX (); if (ScrollX2 <-mleft_menu.getmeasuredwidth ()/2) {scrollanimation ();//full display left menu with animation//ScrollTo (- Mleft_menu.getmeasuredwidth (), 0); IsOpen = true;} else {//scrollTo (0, 0); isOpen = false;} Scrollanimation (); break;default:break;} Return true;//own consumption event}
/** * Move animation */private void Scrollanimation () {LOG.D (tag, "isopenleftmenu==" + isOpen);//Get view at the left of the screen start coordinate and end coordinate int startX = GETSCROLLX (); int endx = 0;if (isOpen) {endx =-mleft_menu.getmeasuredwidth ();} else {}int dx = endx-startx;int dy = 0;in T duration = math.abs (dx) * 2;mscroller.startscroll (startX, 0, DX, dy, duration); invalidate ();//Refresh Interface}
To make the Startscroll () method effective, you must override the view's Computescroll () method (for the Startscroll () method use refer toAndroid scroller Analysis), the code is as follows:
@Overridepublic void Computescroll () {//Determines whether the animation ends if (Mscroller.computescrolloffset ()) {//Returns TRUE to indicate that int currx is not completed = Mscroller.getcurrx (); ScrollTo (Currx, 0); invalidate ();} Super.computescroll ();}

Finally, attached: https://github.com/znouy/SlidingMenu









Customizing the Swipe menu Slidingmenu

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.