Android custom controls Create the simplest side-slip menu in history

Source: Internet
Author: User

Reprint please indicate source: http://blog.csdn.net/lmj623565791/article/details/39185641, this article from "Zhang Hongyang's Blog"

Side-slip menu in many applications will see, recently QQ5.0 side-slip also played a bit of tricks ~ ~ for the side-slip menu, generally we will customize the ViewGroup, and then hide the menu bar, when the finger sliding, through scroller or constantly change leftmargin, etc. , how much is a bit complex, after the completion of the need to deal with the sliding conflict and so on ~ ~ today to bring you a simple implementation, history of the simplest is a bit exaggerated, but it is I have encountered the simplest kind of realization ~ ~ ~

1. Principle Analysis

Since it is side-by-side, is nothing more than the slap big screen, stuffed into two probably two big layout, need to slide can appear another, since so, why do not consider using Android provided Horizontalscrollview it ~

If use Horizontalscrollview, also need in Action_down, action_move inside to listen, judge, constantly change control position? no!!! Horizontalscrollview itself with a sliding function ~ ~

Do you also need to handle all kinds of conflicts manually? no!!! Of course, still need to understand the next event distribution mechanism ~ ~ ~

2.


Well, the main interface made a picture of QQ, the left embezzled a brother layout file ~ ~ Sin ~ who has good-looking layout, pictures, icons God horse, you can give me a point, grateful ~

3. layout file

<com.example.zhy_slidingmenu. Slidingmenu xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" wrap_content "    android:layout_height=" Fill_parent "    android:scrollbars= "None" >    <linearlayout        android:layout_width= "Wrap_content"        android: layout_height= "Fill_parent"        android:orientation= "Horizontal" >        <include layout= "@layout/layout_ Menu "/>        <linearlayout            android:layout_width=" fill_parent "            android:layout_height=" Fill_ Parent "            android:background=" @drawable/qq ">        </LinearLayout>    </linearlayout></ Com.example.zhy_slidingmenu. Slidingmenu>

The first is our custom view, a horizontal linearlayout in one Direction, then a menu layout, and a main layout.

4. Custom Slidingmenu

The next step is our core code.

Package Com.example.zhy_slidingmenu;import Android.content.context;import Android.util.attributeset;import Android.util.typedvalue;import Android.view.motionevent;import Android.view.viewgroup;import Android.widget.horizontalscrollview;import Android.widget.linearlayout;import Com.zhy.utils.ScreenUtils;public Class Slidingmenu extends horizontalscrollview{/** * screen width */private int mscreenwidth;/** * DP */private int Mmenurightpadd ing = 50;/** * Menu width */private int mmenuwidth;private int Mhalfmenuwidth;private boolean once;public slidingmenu (Context C Ontext, AttributeSet attrs) {Super (context, attrs); mscreenwidth = screenutils.getscreenwidth (context);} @Overrideprotected void onmeasure (int widthmeasurespec, int heightmeasurespec) {/** * shows the setting of a width */if (!once) { LinearLayout wrapper = (linearlayout) getchildat (0); ViewGroup menu = (viewgroup) wrapper.getchildat (0); ViewGroup content = (viewgroup) wrapper.getchildat (1);//dp to pxmmenurightpadding = (int) typedvalue.applydimension ( Typedvalue.compLex_unit_dip, Mmenurightpadding, Content.getresources (). Getdisplaymetrics ()); mmenuwidth = MScreenWidth- Mmenurightpadding;mhalfmenuwidth = Mmenuwidth/2;menu.getlayoutparams (). width = Mmenuwidth;content.getlayoutparams ( ). width = mscreenwidth;} Super.onmeasure (Widthmeasurespec, heightmeasurespec);} @Overrideprotected void OnLayout (Boolean changed, int l, int t, int r, int b) {super.onlayout (changed, L, T, R, b); if (chan GED) {//The menu is hidden This.scrollto (mmenuwidth, 0); once = True;}} @Overridepublic boolean ontouchevent (motionevent ev) {int action = ev.getaction (); switch (action) {//up), If the display area is larger than half of the menu width, otherwise hide case MotionEvent.ACTION_UP:int scrollx = GETSCROLLX (); if (Scrollx > Mhalfmenuwidth) This.smoothscrollto (mmenuwidth, 0); Elsethis.smoothscrollto (0, 0); return true;} return super.ontouchevent (EV);}}

Haha, finished ~ above the demo diagram, the use of such a bit of code ~ ~

Code how, short not short ~ In addition to setting the width of these assorted code ~ is processing the sliding code but 10 lines ~ ~ I said the simplest in history is not too good ~

Well, because the code is too short, it does not explain, we look at the comments themselves ~

5. Expansion

Well, just down, we perfect the next procedure, I'm going to first change the menu layout into a ListView to prove that we are not in conflict; then add a property that lets the user configure the value of the margin on the right side of the menu, and then publish a method, click the Auto Open menu for the user to click a button, the menu slowly slide out ~

1. Add a custom attribute

A, first create a new attr.xml under the Values folder and write the following:

<?xml version= "1.0" encoding= "Utf-8"?><resources>    <attr name= "rightpadding" format= "Dimension"/ >    <declare-styleable name= "Slidingmenu" >        <attr name= "rightpadding"/>    </ Declare-styleable></resources>
B. Declaring namespaces and using attributes in layouts

The definition is finished, must be used.

<com.example.zhy_slidingmenu. Slidingmenu xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    xmlns:zhy=" Http://schemas.android.com/apk/res/com.example.zhy_slidingmenu    " Android:layout_width= "Wrap_content"    android:layout_height= "fill_parent"    android:scrollbars= "None"    zhy:rightpadding= "100DP" >

Can see our namespace: xmlns:zhy= "Http://schemas.android.com/apk/res/com.example.zhy_slidingmenu" is HTTP// Schemas.android.com/apk/res/plus our package name;

Our properties: zhy:rightpadding= "100DP" Here I set the 100DP;

Note: Many people ask me, there is no hint to do, so, you clean under the project, if you are lucky, there are hints, ah, good luck ~

C. Get properties in our custom class

Public Slidingmenu (context context, AttributeSet attrs, int defstyle) {Super (context, attrs, defstyle); mscreenwidth = Screenutils.getscreenwidth (context); TypedArray a = Context.gettheme (). Obtainstyledattributes (Attrs,r.styleable.slidingmenu, Defstyle, 0); int n = A.getindexcount (); for (int i = 0, i < n; i++) {int attr = A.getindex (i); switch (attr) {case R.styleable.slidingmenu_right padding://Default 50mMenuRightPadding = A.getdimensionpixelsize (attr, (int) typedvalue.applydimension (Typedvalue.complex _unit_dip, 50f,getresources (). Getdisplaymetrics ()));//default is 10DPbreak;}} A.recycle ();}

In the construction method of three parameters, it is done by Typearray.

OK, so that's OK ~ If you have many custom attributes, follow the steps above

2. Publish an Open menu method

First define a Boolean isopen variable to identify the state of our current menu ~ ~ and then remember to change the state when action_up:

Case MotionEvent.ACTION_UP:int scrollx = GETSCROLLX (); if (Scrollx > Mhalfmenuwidth) {this.smoothscrollto (mmenuwidth , 0); isOpen = false;} Else{this.smoothscrollto (0, 0); IsOpen = true;} return true;}

Here's how to add a method:

/** * Open menu */public void Openmenu () {if (isOpen) return;this.smoothscrollto (0, 0); IsOpen = true;} /** * Close menu */public void Closemenu () {if (IsOpen) {this.smoothscrollto (mmenuwidth, 0); isOpen = false;}} /** * Toggle Menu State */public void Toggle () {if (IsOpen) {Closemenu ();} else{openmenu ();}}

Added two more ...

Below, we pick one to test:

Main layout Add one More button to trigger the Togglemenu () method

Main activity

public class Mainactivity extends Activity{private slidingmenu mmenu; @Overrideprotected void OnCreate (Bundle savedinsta Ncestate) {super.oncreate (savedinstancestate); Requestwindowfeature (Window.feature_no_title); SetContentView ( R.layout.activity_main); Mmenu = (Slidingmenu) Findviewbyid (R.id.id_menu);} public void Togglemenu (view view) {Mmenu.toggle ();}}

Well, look at the present:


We changed padding to 100dp~.

Then click on our button to see the HA effect ~ ~

3. Add a ListView test


Well, ~~listview also tested ~ ~ Everyone can according to their own needs of various changes ~ ~

Yes, today the purpose of testing QQ is to, next time I want to take the above code, Transformation and QQ5.0 The same effect, we are interested can try in advance, QQ menu seems to be hidden in the main interface below the same, give people feel not to draw, we this example can also make that effect, wait and see, the rest is a variety of zoom, transparency of the animation ~ ~ ~


SOURCE Click to download


If you feel good, the evaluation under ~ HA ~






Android custom controls Create the simplest side-slip menu in history

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.