Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自定義側滑菜單:基於 HorizontalScrollView 的實現

編輯:關於 Android 程式設計

實現原理

側滑菜單的本質是「一個可以水平拖動、並在放開後吸附到兩端的容器」。因此最自然的做法是讓自定義控件繼承 HorizontalScrollView——它天生就提供了水平滾動與手勢處理能力,我們只需要重寫測量、布局、滾動等關鍵方法,把「菜單 + 內容」兩塊子視圖排好,並控制吸附行為。

本次實現覆寫的方法:onMeasure()、onTouchEvent()、onLayout()、onScrollChanged()。

如果想加入菜單的縮放、透明度漸變等動畫效果,需要引入第三方庫 nineoldandroids-2.4.0.jar,它讓低版本系統也能使用屬性動畫。

本文實現兩個目標:自定義側滑手勢,以及可配置菜單露出的寬度。

布局文件

菜單本體 left_menu.xml,用一系列 RelativeLayout 排列「圖標 + 文字」的菜單項:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">
            <ImageView
                android:id="@+id/id_img1"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="20dp"
                android:src="@drawable/img_1" />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:layout_toRightOf="@id/id_img1"
                android:text="第一個Item"
                android:textColor="#ffffff"
                android:textSize="20sp" />
        </RelativeLayout>

        <!-- id_img2 / id_img3 / id_img4 / id_img5 結構相同,依次替換
             圖片資源與文案:第二個Item、第三個Item、第四個Item、第五個Item -->
    </LinearLayout>
</RelativeLayout>

主界面 activity_main.xml,用我們的自定義 SlidingMenu 包住「菜單 + 內容」:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:micro="https://schemas.android.com/apk/res/com.micro.slidingmenu"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/img_frame_background">

    <com.micro.slidingview.slidingmenu.SlidingMenu
        android:id="@+id/id_menu"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        micro:rightPadding="150dp">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <include layout="@layout/left_menu" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/qq">
                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:onClick="toggleMenu"
                    android:text="切換" />
            </LinearLayout>
        </LinearLayout>
    </com.micro.slidingview.slidingmenu.SlidingMenu>
</RelativeLayout>

自定義屬性的聲明文件 values/attr.xml:

<resources>
    <declare-styleable name="SlidingMenu">
        <attr name="rightPadding" format="dimension" />
    </declare-styleable>
</resources>

SlidingMenu 核心代碼

public class SlidingMenu extends HorizontalScrollView {

    private LinearLayout mWrapper;   // 總容器
    private ViewGroup mMenu;         // 菜單子視圖
    private ViewGroup mContent;      // 內容子視圖
    private int mScreenWidth;        // 屏幕寬度
    private int mMenuRightPadding = 50; // 菜單距屏幕右側的留白(dp)
    private int mMenuWidth;          // 菜單寬度
    private boolean isOpen;          // 菜單是否打開

    public SlidingMenu(Context context) {
        this(context, null);
    }

    public SlidingMenu(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SlidingMenu(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        // 讀取自定義屬性
        TypedArray ta = context.getTheme()
                .obtainStyledAttributes(attrs, R.styleable.SlidingMenu, defStyle, 0);
        int n = ta.getIndexCount();
        for (int i = 0; i < n; i++) {
            int attr = ta.getIndex(i);
            switch (attr) {
                case R.styleable.SlidingMenu_rightPadding:
                    mMenuRightPadding = ta.getDimensionPixelSize(attr,
                            (int) TypedValue.applyDimension(
                                    TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics()));
                    break;
            }
        }
        ta.recycle();

        // 屏幕寬度
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        mScreenWidth = wm.getDefaultDisplay().getWidth();

        mWrapper = (LinearLayout) getChildAt(0);
        mMenu = (ViewGroup) mWrapper.getChildAt(0);
        mContent = (ViewGroup) mWrapper.getChildAt(1);
        mMenuWidth = mScreenWidth - mMenuRightPadding;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // 讓菜單佔據 mMenuWidth,內容佔滿全屏
        mMenu.getLayoutParams().width = mMenuWidth;
        mContent.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);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_UP) {
            int scrollX = getScrollX();
            if (scrollX >= mMenuWidth / 2) {
                // 超過一半,吸附到收起
                this.smoothScrollTo(mMenuWidth, 0);
                isOpen = false;
            } else {
                this.smoothScrollTo(0, 0);
                isOpen = true;
            }
            return true;
        }
        return super.onTouchEvent(ev);
    }

    /** 打開菜單 */
    public void openMenu() {
        if (isOpen) return;
        this.smoothScrollTo(0, 0);
        isOpen = true;
    }

    /** 收起菜單 */
    public void closeMenu() {
        if (!isOpen) return;
        this.smoothScrollTo(mMenuWidth, 0);
        isOpen = false;
    }

    /** 切換菜單 */
    public void toggle() {
        if (isOpen) closeMenu(); else openMenu();
    }

    /** 滾動過程中驅動菜單的視差效果 */
    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        float scale = l * 1.0f / mMenuWidth;

        // 菜單跟隨滾動平移,只保留 0.8 倍的位移量,形成視差
        ViewHelper.setTranslationX(mMenu, mMenuWidth * scale * 0.8f);

        // 若需要菜單縮放+淡入效果,可繼續加入:
        // float leftScale = 1.0f - scale * 0.3f;
        // float leftAlpha = 0.6f + 0.4f * (1 - scale);
        // ViewHelper.setScaleX(mMenu, leftScale);
        // ViewHelper.setScaleY(mMenu, leftScale);
        // ViewHelper.setAlpha(mMenu, leftAlpha);
        // ViewHelper.setPivotX(mMenu, 0);
        // ViewHelper.setPivotY(mMenu, mMenu.getHeight() / 2);
        //
        // 內容層反向縮放:
        // float rightScale = 0.7f + 0.3f * scale;
        // ViewHelper.setPivotX(mContent, 0);
        // ViewHelper.setPivotY(mContent, mContent.getHeight() / 2);
        // ViewHelper.setScaleX(mContent, rightScale);
        // ViewHelper.setScaleY(mContent, rightScale);
    }
}

幾個設計要點值得留意:菜單寬度由 屏幕寬 - rightPadding 決定,改這個值就能調整露出比例;onTouchEvent 裡用「是否超過一半」作為吸附判據,手感最自然;onScrollChanged 是驅動視差動畫的心臟,註釋掉的那些代碼就是常見的縮放加淡變效果,感興趣可以自己打開試。

Activity 中的調用

public class MainActivity extends Activity {

    private SlidingMenu leftMenu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        leftMenu = (SlidingMenu) findViewById(R.id.id_menu);
    }

    /** 供布局中的 Button 通過 onClick 調用 */
    public void toggleMenu(View v) {
        leftMenu.toggle();
    }
}

效果

整套實現的關鍵就三點:用 HorizontalScrollView 白拿滾動能力、用 onLayout 設定初始收起的偏移、用 onScrollChanged 做視差。理解了這三點,換成 DrawerLayout 或者加更多動畫都只是時間問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved