Android slide menu by yourself

Source: Internet
Author: User

Android slide menu by yourself
In today's android Application Design, a mainstream design method is to have a slide menu, as shown in an image: To achieve this slide effect, we used the SlidingMenu open-source framework most before 5.0. After 5.0, google launched its own slide implementation library, which is DrawerLayout. Its usage is simpler than SlidingMenu, and because google's son, people are more inclined to use DrawerLayout now, but in other words, these are good things implemented by others. We just want to use them. For internal principles, many programmers do not quite understand this. In the next article, I will use some basic controls in android to achieve this similar effect. Of course, there may be many ways to achieve this, however, the basic principle is similar.

 

First, we will use a control: HorizontalScrollView. We can see from the name that it is a horizontal sliding control, that is, when the content is larger than the screen width, you can slide left and right to display content beyond the screen.

Step 1: Write down the menu Layout

<span style="font-size:18px;"><span style="font-family:KaiTi_GB2312;font-size:14px;"><!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%2D%2D%3E--><relativelayout android:layout_height="match_parent" android:layout_width="match_parent" xmlns:android="http://schemas.android.com/apk/res/android">    <linearlayout android:layout_centerinparent="true" android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical">        <relativelayout android:layout_height="wrap_content" android:layout_width="wrap_content">            <imageview android:id="@+id/img1" android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="@drawable/ic_launcher">            <textview android:id="@+id/text1" android:layout_centervertical="true" android:layout_height="wrap_content" android:layout_torightof="@id/img1" android:layout_width="wrap_content" android:text="item1">        </textview></imageview></relativelayout>        <relativelayout android:layout_height="wrap_content" android:layout_width="wrap_content">            <imageview android:id="@+id/img2" android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="@drawable/ic_launcher">            <textview android:id="@+id/text2" android:layout_centervertical="true" android:layout_height="wrap_content" android:layout_torightof="@id/img2" android:layout_width="wrap_content" android:text="item1">        </textview></imageview></relativelayout>        <relativelayout android:layout_height="wrap_content" android:layout_width="wrap_content">            <imageview android:id="@+id/img3" android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="@drawable/ic_launcher">            <textview android:id="@+id/text3" android:layout_centervertical="true" android:layout_height="wrap_content" android:layout_torightof="@id/img3" android:layout_width="wrap_content" android:text="item1">        </textview></imageview></relativelayout>        <relativelayout android:layout_height="wrap_content" android:layout_width="wrap_content">            <imageview android:id="@+id/img4" android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="@drawable/ic_launcher">            <textview android:id="@+id/text4" android:layout_centervertical="true" android:layout_height="wrap_content" android:layout_torightof="@id/img4" android:layout_width="wrap_content" android:text="item1">        </textview></imageview></relativelayout>        <relativelayout android:layout_height="wrap_content" android:layout_width="wrap_content">            <imageview android:id="@+id/img5" android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="@drawable/ic_launcher">            <textview android:id="@+id/text5" android:layout_centervertical="true" android:layout_height="wrap_content" android:layout_torightof="@id/img5" android:layout_width="wrap_content" android:text="item1">        </textview></imageview></relativelayout>    </linearlayout></relativelayout></span></span>
Step 2: write out the overall layout
<span style="font-size:18px;"><span style="font-family:KaiTi_GB2312;font-size:14px;"><!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%2D%2D%3E--><linearlayout android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"><googleplay.xiaokai.com.qq.slidmenu android:background="@drawable/img_frame_background" android:id="@+id/horscrview" android:layout_height="match_parent" android:layout_width="wrap_content" android:scrollbars="none">    <linearlayout android:layout_height="match_parent" android:layout_width="wrap_content" android:orientation="horizontal">        <include layout="@layout/left_menulayout">        <linearlayout android:background="@drawable/qq" android:layout_height="match_parent" android:layout_width="match_parent">        </linearlayout>    </include></linearlayout></googleplay.xiaokai.com.qq.slidmenu></linearlayout></span></span>
Note: googplay.xiaokai.com. qq. SlidMenu is the control we want to implement.Step 3: Inherit HorizontalScrollView to implement Custom Controls
<Span style = "font-size: 18px;"> package googleplay.xiaokai.com. qq; import android. content. context; import android. util. attributeSet; import android. util. displayMetrics; import android. util. typedValue; import android. view. motionEvent; import android. view. viewGroup; import android. view. windowManager; import android. widget. horizontalScrollView; import android. widget. linearLayout;/*** Created by Sun xiaokai on 2016/3/27. */Public class SlidMenu extends detail {int mScreenWit; // screen width int mRightWithScr; LinearLayout mWrap; ViewGroup mMenu; ViewGroup mContent; int mMenuWidth; private boolean flag; public SlidMenu, attributeSet attrs) {super (context, attrs); // obtain the screen width WindowManager winmana = (WindowManager) context. getSystemService (context. WINDOW_SERVICE); DisplayMetrics metris = new DisplayMetrics (); winmana. getdefadisplay display (). getMetrics (metris); mScreenWit = metris. widthPixels; // The pixel is obtained. // convert 50dp to mRightWithScr = (int) TypedValue. applyDimension (TypedValue. COMPLEX_UNIT_DIP, 50, context. getResources (). getDisplayMetrics ();} public SlidMenu (Context context) {super (context) ;}@ Override protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {if (! Flag) {mWrap = (LinearLayout) getChildAt (0); // you can obtain the first child control mMenu = (ViewGroup) mWrap in this space. getChildAt (0); // obtain menu mContent = (ViewGroup) mWrap. getChildAt (1); // get the content control mMenuWidth = mMenu. getLayoutParams (). width = mScreenWit-mRightWithScr; // The width of the slide menu is the screen width minus 50dp mContent. getLayoutParams (). width = mScreenWit; // set the content control width flag = true;} super. onMeasure (widthMeasureSpec, heightMeasureSpec);}/* to hide the menu, set the offset */@ Override protected void onLayout (boolean changed, int l, int t, int r, int B) {if (changed) {this. scrollTo (mMenuWidth, 0); // move to the left} super. onLayout (changed, l, t, r, B) ;}@ Override public boolean onTouchEvent (MotionEvent ev) {int action = ev. getAction (); switch (action) {case MotionEvent. ACTION_UP: int scx = getScrollX (); // It is the X-axis offset of the upper left corner of the current view relative to the upper left corner of the parent view. if (scx> = mMenuWidth/2) {this. smoothScrollTo (mMenuWidth, 0);} else {this. smoothScrollTo (0, 0);} return true;} return super. onTouchEvent (ev) ;}}</span>
At this time, the program is not flexible enough. For example, if you want to adjust the menu distance from the right of the screen, what should you do? In this case, we can customize an attribute. Step 1:Create an attr. xml file in the values folder; Step 2: Define attributes in the file
<Span style = "font-size: 18px;"> <! -- {Cke_protected} {C} % 3C! % 2D % 2D % 3 Fxml % 20 version % 3D % 221.0% 20 encoding % 3D % 22utf-8% 22% 3F % 2D % 2D % 3E --> <resources> <declare-styleable name = "SlidMenu"> <attr format = "dimension" name = "RithtPadding"> </attr> </declare-styleable> </resources> RithtPadding is the name of the custom attribute.; <! -- {Cke_protected} {C} % 3C! % 2D % 2D % 3 Fxml % 20 version % 3D % 221.0% 20 encoding % 3D % 22utf-8% 22% 3F % 2D % 2D % 3E --> <linearlayout xmlns: my = "http://schemas.android.com/apk/res-auto"> xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android: orientation = "vertical" android: layout_width = "match_parent" android: layout_height = "match_parent"> <googleplay.xiaokai.com. qq. slidmenu android: background = "@ drawable/img_frame_background" android: id = "@ + id/horscrview" android: layout_height = "match_parent" android: layout_width = "wrap_content" android: scrollbars = "none" my: rithtpadding = "100dp"> <linearlayout android: layout_height = "match_parent" android: layout_width = "wrap_content" android: orientation = "horizontal"> <include layout = "@ layout/left_menulayout"> <linearlayout android: background = "@ drawable/qq" android: layout_height = "match_parent" android: layout_width = "match_parent"> </linearlayout> </include> </linearlayout> </googleplay.xiaokai.com. qq. slidmenu> </linearlayout> </span>
  Step 3: Get the attribute values in the layout file in the Code and perform corresponding operations
<Span style = "font-size: 18px;"> public SlidMenu (Context context, AttributeSet attrs, int defStyleAttr) {super (context, attrs, defStyleAttr ); // obtain the screen width WindowManager winmana = (WindowManager) context. getSystemService (context. WINDOW_SERVICE); DisplayMetrics metris = new DisplayMetrics (); winmana. getdefadisplay display (). getMetrics (metris); mScreenWit = metris. widthPixels; // The pixel <span style = "color: # 3366ff;"> TypedArray array = context. getTheme (). obtainStyledAttributes (attrs, R. styleable. slidMenu, defStyleAttr, 0); int n = array. getIndexCount (); for (int I = 0; I <n; I ++) {attr = "array. getIndex (I); "case =" "int =" "mrightwithscr =" array. getDimensionPixelSize (attr, (int) "r. styleable. slidmenu_rithtpadding: = "" span = "" switch = "" >}</n; I ++) {></span> </span>
Well, this time seems perfect, huh? No, people have a click button in the upper left corner of the slide. One click, the menu will come out. Another click, and the menu will go in. Okay, let's implement it! You only need two steps: Step 1: Add the following three methods to the custom control:
<Span style = "font-size: 18px;">/* Open the menu */public void openMenu () {if (isOpen) return; else {this. smoothScrollTo (); // open isOpen = true;}/* close menu */public void closeMenu () {if (! IsOpen) {return;} else {this. smoothScrollTo (mMenuWidth, 0); isOpen = false;}/* Switch menu */public void toggle () {if (isOpen) {closeMenu ();} else {openMenu () ;}</span>
Step 2: Define a button in the layout file (this will happen, I will not post code), and then directly call it when using the control by clicking the method.
<Span style = "font-size: 18px;"> public class MainActivity extends AppCompatActivity {private SlidMenu slidmenu; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); supportRequestWindowFeature (Window. FEATURE_NO_TITLE); <span style = "font-family: Arial, Helvetica, sans-serif;" >/// </span> <span style = "font-family: Arial, helvetica, sans-serif; "> If the inherited ActionBar An error is returned for an Activity or AppCompatActivity. </span> <span style = "font-family: Arial, Helvetica, sans-serif;"> if you insist on using this method, inherit Activity. </Span> // If you inherit AppCompatActivity or ActionBarActivity, call the following method to replace the above method. // supportRequestWindowFeature (Window. FEATURE_NO_TITLE); setContentView (R. layout. activity_main); slidmenu = (SlidMenu) findViewById (R. id. horscrview);} public void toggle (View view) {slidmenu. toggle () ;}}</span>
OK, I'm done. This time is all right! Well, it seems okay, but we can still make better results! The implementation of this effect is also very simple, mainly through the property animation, add the following code to the custom control:
<Span style = "font-size: 18px;">/*** when a scroll occurs */@ Override protected void onScrollChanged (int l, int t, int oldl, int oldt) {super. onScrollChanged (l, t, oldl, oldt);/*** difference 1: content area 1.0 ~ 0.7 scale: 1.0 ~ 0.0 0.7 + 0.3 * scale ** difference 2: menu offset needs to be modified ** difference 3: There are scaling and transparency changes in the menu display ZOOM: 0.7 ~ 1.0 1.0-scale * 0.3 transparency 0.6 ~ 1.0*0.6 + 0.4 * (1-scale); **/float rightScale = 0.7f + 0.3f * scale; float leftScale = 1.0f-scale * 0.3f; float leftAlpha = 0.6f + 0.4f * (1-scale); // call the property animation and set TranslationX ViewHelper. setTranslationX (mMenu, mMenuWidth * scale * 0.8f); ViewHelper. setScaleX (mMenu, leftScale); ViewHelper. setScaleY (mMenu, leftScale); ViewHelper. setAlpha (mMenu, leftAlpha); // you can specify the center point for content scaling. setmediatx (mContent, 0); ViewHelper. setequalty (mContent, mContent. getHeight ()/2); ViewHelper. setScaleX (mContent, rightScale); ViewHelper. setScaleY (mContent, rightScale) ;}</span>
  Well, this is the success!

Figure:

 

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.