The android sliding menu framework is completely parsed to teach you how to implement sliding menu effects in one minute

Source: Internet
Author: User

Reprinted please indicate the source: http://blog.csdn.net/guolin_blog/article/details/8744400

Previously, I introduced the simplest implementation method of sliding menus in history. If you forget the implementation principles or friends you have not read, read the previous article first.Android sliding menu effect implementation, similar to the sliding effect of the Renren client, the simplest side slide implementation in historyBecause the sliding menu framework we want to implement today is based on the same principle.

As mentioned in the previous article, if there are many activities in your application that need to be added with the sliding menu function, therefore, each activity requires hundreds of lines of code to achieve the effect, and a simple implementation scheme of sliding menus is useless. Therefore, we need to implement a sliding menu framework today, and then the sliding menu function can be introduced in any activity for one minute.

First, let's talk about the implementation principle. It is a sliding menu framework. To put it bluntly, it is also very simple. That is, we can customize a layout to implement the sliding menu function in this custom layout, then, as long as we introduce our custom layout in the activity layout file, this activity has the function of sliding menu. The principle is over, isn't it easy? Let's implement it.

Create an android project in eclipse. The project name is renrenslanguinglayout.

Create a new class named slidinglayout, which inherits from linearlayout and implements the ontouchlistener interface. The Code is as follows:

Public class slidinglayout extends linearlayout implements ontouchlistener {/*** the speed at which fingers slide when scrolling and hiding the left layout. */Public static final int snap_velocity = 200;/*** screen width value. */Private int screenwidth;/*** the left layout can slide to the left edge at most. The value is determined by the layout width on the left. After marginleft reaches this value, it cannot be reduced. */Private int leftedge;/*** the left-side layout can slide to the right edge at most. The constant value is 0, that is, after marginleft reaches 0, it cannot be increased. */Private int rightedge = 0;/*** when the left-side layout is fully displayed, the width value is left to the right-side layout. */Private int leftlayoutpadding = 80;/*** record the abscissa when the finger is pressed. */Private float xdown;/*** record the abscissa when the finger moves. */Private float xmove;/*** record the abscissa when the mobile phone is lifted. */Private float xup;/*** the left-side layout is currently displayed or hidden. This value is changed only when it is fully displayed or hidden. This value is invalid during sliding. */Private Boolean isleftlayoutvisible;/*** layout object on the left. */Private view leftlayout;/*** layout object on the right. */Private view rightlayout;/*** is used to listen to views of Slide events. */Private view mbindview;/*** left-side layout parameter. You can use this parameter to determine the width of the left-side layout and change the leftmargin value. */Private marginlayoutparams leftlayoutparams;/*** parameters of the right layout, which can be used to determine the width of the right layout. */Private marginlayoutparams rightlayoutparams;/*** is used to calculate the speed of finger sliding. */Private velocitytracker mvelocitytracker;/*** rewrite the slidinglayout constructor to obtain the screen width. ** @ Param context * @ Param attrs */Public slidinglayout (context, attributeset attrs) {super (context, attrs); windowmanager WM = (windowmanager) context. getsystemservice (context. window_service); screenwidth = WM. getdefadisplay display (). getwidth ();}/*** bind the view to listen to the slide event, that is, to display and hide the left layout only when the bound view slides. ** @ Param BindView * view object to be bound. */Public void setscrollevent (view BindView) {mbindview = BindView; mbindview. setontouchlistener (this);}/*** scroll the screen to the left-side layout interface and set the scroll speed to 30. */Public void scrolltoleftlayout () {New scrolltask(cmd.exe cute (30);}/*** scroll the screen to the right-side layout interface and set the scroll speed to-30. */Public void scrolltorightlayout () {New scrolltask(cmd.exe cute (-30);}/*** whether the left-side layout is completely displayed or completely hidden. This value is invalid during the sliding process. ** @ Return returns true if the left-side layout is completely displayed, and false if the layout is completely hidden. */Public Boolean isleftlayoutvisible () {return isleftlayoutvisible;}/*** reset the parameters of the Left layout and right layout in onlayout. * // @ Overrideprotected void onlayout (Boolean changed, int L, int T, int R, int B) {super. onlayout (changed, L, t, R, B); If (changed) {// obtain the left-side layout object leftlayout = getchildat (0); leftlayoutparams = (marginlayoutparams) leftlayout. getlayoutparams (); // reset the width of the left-side layout object to the screen width minus leftlayoutpaddingleftlayoutparams. width = screenwidth-leftlayoutpadding; // set leftedge =-leftlayoutparams. width; leftlayoutpar AMS. leftmargin = leftedge; leftlayout. setlayoutparams (leftlayoutparams); // obtain the right layout object rightlayout = getchildat (1); rightlayoutparams = (marginlayoutparams) rightlayout. getlayoutparams (); rightlayoutparams. width = screenwidth; rightlayout. setlayoutparams (rightlayoutparams) ;}@ overridepublic Boolean ontouch (view V, motionevent event) {createvelocitytracker (event); Switch (event. getaction () {Case motioneven T. action_down: // the x-axis xdown = event when the finger is pressed. getrawx (); break; Case motionevent. action_move: // when the finger moves, compare the abscissa when pressed to calculate the moving distance, to adjust the leftmargin value of the Left layout, so as to display and hide the left layout 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 = rightedge;} leftlayout. setlayoutparams (leftlayoutparams); break; Case motionevent. action_up: // when the finger is raised, judge the intent of the current gesture, and decide whether to scroll to the left layout or to the right layout xup = event. getrawx (); If (wanttoshowleftlayout () {If (then () {scrolltoleftlayout ();} else {scrolltorightlayout () ;}} else if (wanttoshowrightl Ayout () {If (shouldscrolltocontent () {scrolltorightlayout ();} else {scrolltoleftlayout () ;}} else (); break ;} return isbindbasiclayout ();} /*** determine whether the intent of the current gesture is to display the layout on the right. If the distance between the fingers is negative and the current left layout is visible, the current gesture is considered to display the right layout. ** @ Return: returns true if you want to display the layout on the right side of the current gesture. Otherwise, false is returned. */Private Boolean wanttoshowrightlayout () {return xup-xdown <0 & isleftlayoutvisible;}/*** determines whether the intent of the current gesture is to display the layout on the left. If the distance between the fingers is positive and the current left layout is invisible, the current gesture is considered to display the left layout. ** @ Return: returns true if you want to display the layout on the left side of the current gesture. Otherwise, false is returned. */Private Boolean wanttoshowleftlayout () {return xup-xdown> 0 &&! Isleftlayoutvisible;}/*** determines whether to scroll to display the left layout. If the finger movement distance is greater than 1/2 of the screen, or the finger movement speed is greater than snap_velocity, * the layout on the left should be displayed by scrolling. ** @ Return: returns true if the layout on the left is displayed in scroll mode. Otherwise, false is returned. */Private Boolean shouldscrolltoleftlayout () {return xup-xdown> screenwidth/2 | getscrollvelocity ()> snap_velocity;}/*** determines whether to scroll to display the layout on the right. If the finger movement distance plus leftlayoutpadding is greater than 1/2 of the screen, * or the finger movement speed is greater than snap_velocity, the layout on the right should be displayed by scrolling. ** @ Return: returns true if the layout on the right is displayed in scroll mode. Otherwise, false is returned. */Private Boolean shouldscrolltocontent () {return xdown-xup + leftlayoutpadding> screenwidth/2 | getscrollvelocity ()> snap_velocity ;} /*** determine whether the view bound to a sliding event is a basic layout. custom layout is not supported. Only four basic layout types are supported. * absolutelayout has been discarded. ** @ Return if the view bound to a sliding event is linearlayout, relativelayout, framelayout, and * One of tablelayout, true is returned; otherwise, false is returned. */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 ();}/*** create a velocitytracker object and add the touch event to the velocitytracker. ** @ Param event * Sliding event of the layout listening control on the right */private void createvelocitytracker (motionevent event) {If (mvelocitytracker = NULL) {mvelocitytracker = velocitytracker. obtain ();} mvelocitytracker. addmovement (event);}/*** get the Sliding Speed of the finger on the listener view in the right layout. ** @ Return sliding speed, measured in the unit of how many pixels are moved per second. */Private int getscrollvelocity () {mvelocitytracker. computecurrentvelocity (1000); int velocity = (INT) mvelocitytracker. getxvelocity (); Return math. ABS (velocity);}/*** reclaim the velocitytracker object. */Private void recyclevelocitytracker () {mvelocitytracker. recycle (); mvelocitytracker = NULL;} class scrolltask extends asynctask <integer, integer, integer >{@ overrideprotected integer doinbackground (integer... speed) {int leftmargin = leftlayoutparams. leftmargin; // scroll the interface based on the input speed. When the scroll reaches the Left or Right boundary, the page jumps out of the loop. While (true) {leftmargin = leftmargin + speed [0]; If (leftmargin> rightedge) {leftmargin = rightedge; break;} If (leftmargin <leftedge) {leftmargin = leftedge; break;} publishprogress (leftmargin); // in order to have a rolling effect, the thread sleeps for 20 milliseconds each cycle, so that you can see the scroll animation with the naked eye. Sleep (20);} If (speed [0]> 0) {isleftlayoutvisible = true;} else {isleftlayoutvisible = false;} return leftmargin ;} @ overrideprotected void onprogressupdate (integer... leftmargin) {leftlayoutparams. leftmargin = leftmargin [0]; leftlayout. setlayoutparams (leftlayoutparams);} @ overrideprotected void onpostexecute (integer leftmargin) {leftlayoutparams. leftmargin = leftmargin; leftlayout. setlayoutparams (leftla Youtparams) ;}}/*** specifies the number of milliseconds for the current thread to sleep. ** @ Param millis * specifies the duration of sleep of the current thread, in milliseconds */private void sleep (long millis) {try {thread. sleep (millis);} catch (interruptedexception e) {e. printstacktrace ();}}}

As you can see, I believe everyone will feel familiar with these codes. That's right. Basically, the code is similar to the Code in the previous article, except that the code was written in the activity before, and now we moved to the custom view.

Next, let me explain a different part from the previous one. We can see that the onlayout method is rewritten here, andGetchildat (0)The obtained layout is used as the left layout.Getchildat (1)The obtained layout is used as the right layout. Define the width of the Left layout as screen width minus leftlayoutpadding and the width of the right layout as screen width. Then let the left layout be removed from the screen, so that only the right layout can be seen. Therefore, we can also see that the prerequisite for slidinglayout layout must provide two sub-elements for this layout. The first element will be removed from the screen as the left layout, the second element is displayed on the screen as the right layout.

Then let's take a look at the setscrollevent method. This method receives a view as a parameter and binds a touch event to this view. What does this mean? Let's imagine a scenario. If the layout on the right is a linearlayout, I can monitor the touch event on linearlayout to control the display and hiding of the layout on the left. However, if a listview is added to the linearlayout layout on the right, and the listview is full of the entire linearlayout, linearlayout cannot be touched again at this time, at this time, we need to register the touch event to the listview. The setscrollevent method provides a registration interface. The touch event is registered to the input view.

Finally, there is a strange method, isbindbasiclayout. This method determines whether the view of the registered touch event is one of the four basic la S. If yes, true is returned; otherwise, false is returned. This method plays a very important role in the entire slidinglayout, mainly used to control whether the ontouch event returns true or false, which will affect whether the view function in the layout is available. Because Android's event forwarding mechanism is involved in it, and there are a lot of content, I will not explain it in detail here. I will write a special article to introduce Android's event mechanism in the future. Here, we will simply remember that if it is a basic layout, true will be returned; otherwise, false will be returned.

Now that we have finished writing slidinglayout, let's witness the miraculous moment. Let's take a look at how to introduce the sliding menu function in the activity in one minute.

Create or open the activity_main.xml file in the layout directory and add the following code:

<Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" xmlns: Tools = "http://schemas.android.com/tools" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent" Android: Orientation = "horizontal" tools: context = ". mainactivity "> <! -- Use a custom slide layout. orientation must be in the horizontal direction --> <COM. example. slide. slidinglayout Android: Id = "@ + ID/slidinglayout" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent" Android: Orientation = "horizontal"> <! -- The root node of the slide layout can have only two child elements. These two child elements must be one of the four basic la S: linearlayout, relativelayout, framelayout, or tablelayout. The first child element is used as the left layout and hidden after initialization. The second child element is used as the right layout, that is, the main layout of the current activity. --> <Relativelayout Android: Id = "@ + ID/menu" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent" Android: background = "#00 CCFF"> <textview Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: layout_centerinparent = "true" Android: TEXT = "this is menu" Android: textcolor = "#000000" Android: textsize = "28sp"/> </relativelayout> <linearlayout Android: id = "@ + ID/content" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent" Android: Orientation = "vertical"> <button Android: id = "@ + ID/menubutton" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: text = "menu"/> <listview Android: id = "@ + ID/contentlist" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent"> </listview> </linearlayout> </COM. example. slide. slidinglayout> </linearlayout>

We can see that in the root layout, we introduce the custom Layout com. example. Slide. slidinglayout, and then add two child elements, relativelayout and linearlayout. In relativelayout, A textview is added. In linearlayout, we add a button and a listview.

Then create or open mainactivity as the main activity of the program and add the Code:

Public class mainactivity extends activity {/*** slide layout object, used to show or hide the left menu layout by swiping your fingers. */Private slidinglayout;/*** click the menu button to display the layout on the left and click hide the layout on the left. */Private button menubutton;/*** place it in the content layout listview. */Private listview contentlistview;/*** applies to the contentlistview adapter. */Private arrayadapter <string> contentlistadapter;/*** fill in the data source of contentlistadapter. */Private string [] contentitems = {"content item 1", "content item 2", "content item 3", "content item 4", "content item 5 ", "content item 6", "content item 7", "content item 8", "content item 9", "content item 10", "content item 11 ", "content item 12", "content item 13", "content item 14", "content item 15", "content item 16" };@ overrideprotected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); slidinglayout = (slidinglayout) findviewbyid (R. id. slidinglayout); menubutton = (button) findviewbyid (R. id. menubutton); contentlistview = (listview) findviewbyid (R. id. contentlist); contentlistadapter = new arrayadapter <string> (this, android. r. layout. simple_list_item_1, contentitems); contentlistview. setadapter (contentlistadapter); // bind the listening slide event to the slidinglayout on the contentlistview. setscrollevent (contentlistview); menubutton. setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {// click menu to display the left layout, and then click hide the left layout function if (slidinglayout. isleftlayoutvisible () {slidinglayout. scrolltorightlayout ();} else {slidinglayout. scrolltoleftlayout ();}}});}}

The focus of the above Code is to call the setscrollevent method of slidinglayout to register a touch event for listview. At the same time, a click event is added to the button to show the left layout by clicking it, and then click to hide the left layout.

Finally, the old rule shows the androidmanifest. XML code:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.slide"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="8" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@android:style/Theme.NoTitleBar" >        <activity            android:name="com.example.slide.MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>

Now, let's run it. First, when the program is opened, the right layout is displayed. Slide to the right of the interface with your fingers to see the layout on the left.

When the left-side layout is fully displayed, It is shown as follows:

In addition, you can click the menu button to control the display and hiding of the layout on the left. You can try it on your own.

With the custom layout, you can add the sliding menu function to any activity in a simple way, even if you have more activity, you don't have to worry about it, the sliding menu is properly introduced in one minute.

To sum up, it takes only two steps to add the sliding menu function to the activity:

1. introduce our custom Layout in layout of acitivty, and add two direct sub-elements to this layout.

2. Use the setscrollevent method in the activity to register a touch event for a view.

Now, today's explanation is over. If you have any questions, please leave a message below.

Click here to download the source code

Supplement:

Since this article was written earlier, there were still many problems with the sliding menu that was written at that time. I then made a lot of changes to the above Code and wrote a sliding menu of the corrected version, this version mainly fixes the following:

1. Change the sliding mode to the overwrite mode.

2. listview does not slide out the menu easily when Scrolling up or down.

3. Events on the Content layout are blocked while sliding.

4. When the menu layout is displayed, click the content layout on the right to hide the menu.

5. Fixed the bug where the menu may be temporarily displayed when the program is opened and then instantly disappears.

Download the revised version source code. Click here

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.