自定义View
public class SlidingMenu extends HorizontalScrollView { private int mScreenWidth; private int mMenuRightPadding = 50; // dp private int mMenuWidth; private int mHalfMenuWidth; private boolean once; private boolean isOpen; public SlidingMenu(Context context, AttributeSet attrs) { super(context, attrs); mScreenWidth = Utils.getScreenWidth(context); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (!once) { LinearLayout wrapper = (LinearLayout) getChildAt(0); ViewGroup menu = (ViewGroup) wrapper.getChildAt(0); ViewGroup content = (ViewGroup) wrapper.getChildAt(1); mMenuRightPadding = (int) Utils.dp2px(mMenuRightPadding, content); mMenuWidth = mScreenWidth - mMenuRightPadding; mHalfMenuWidth = mMenuWidth / 2; menu.getLayoutParams().width = mMenuWidth; content.getLayoutParams().width = mScreenWidth; } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); if (changed) { // 隐藏菜单 this.scrollTo(mMenuWidth, 0); once = true; } } @Override public boolean onTouchEvent(MotionEvent ev) { int action = ev.getAction(); // 如果现实区域大于菜单一般,则显示,否则隐藏 if (action == MotionEvent.ACTION_UP) { int scrollX = getScrollX(); if (scrollX > mHalfMenuWidth) { this.smoothScrollTo(mMenuWidth, 0); isOpen = false; } else { this.smoothScrollTo(0, 0); isOpen = true; } return true; } return super.onTouchEvent(ev); } ///添加操作方法 public void openMenu(){ if(!isOpen){ this.smoothScrollTo(0, 0); isOpen = true; } } public void closeMenu(){ if(isOpen){ this.smoothScrollTo(mMenuWidth, 0); isOpen = false; } } public void toggle(){ if(isOpen){ closeMenu(); }else{ openMenu(); } } }
布局文件中应用自定义View
<com.slide.SlidingMenu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/slide_menu" android:layout_width="wrap_content" android:layout_height="match_parent" android:scrollbars="none" > <LinearLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:orientation="horizontal" > <include android:id="@+id/menu" layout="@layout/activity_main"/> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/main_bg" android:orientation="vertical" > <Button android:id="@+id/toggle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="弹出菜单"/> </LinearLayout> </LinearLayout> </com.slide.SlidingMenu>