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

Android 自定義控件:用 HorizontalScrollView 打造極簡側滑菜單

編輯:關於 Android 程式設計

側滑菜單在現在的應用裡幾乎隨處可見,QQ5.0 甚至還在側滑上玩了點花樣。一般做法是自定義 ViewGroup,把菜單藏在畫面外,手指滑動時透過 Scroller 或不斷改變 leftMargin 來移動,完成後還得處理滑動衝突,多少都有點複雜。

今天提供一個更省事的做法。「史上最簡單」難免誇張,但這確實是我目前見過最省事的一種實作。

一、原理分析

側滑的本質是:在巴掌大的螢幕裡塞進大約兩巴掌寬的版面,滑動後另一塊才露出來。既然如此,何不直接用 Android 提供的 HorizontalScrollView?

用了它,還需要在 ACTION_DOWN、ACTION_MOVE 裡自己監聽、判斷、不斷改變元件位置嗎?不需要——HorizontalScrollView 本身就自帶滑動能力。

還需要自己處理各種事件衝突嗎?也不需要。當然,事件分發機制還是要懂,只是不用在這裡手寫。

二、效果預覽

主畫面用了 QQ 的圖片,左邊借用了一位朋友的版面,在此致謝。

三、版面檔

<com.example.zhy_slidingmenu.SlidingMenu
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_height="fill_parent"
    android:layout_width="wrap_content"
    android:scrollbars="none">

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

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

        <LinearLayout
            android:background="@drawable/qq"
            android:layout_height="fill_parent"
            android:layout_width="fill_parent">
        </LinearLayout>

    </LinearLayout>

</com.example.zhy_slidingmenu.SlidingMenu>

自定義的 View 裡放一個水平方向的 LinearLayout,裡面分別是菜單版面與主內容版面。

四、自定義 SlidingMenu

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 {

    /** 螢幕寬度 */
    private int mScreenWidth;
    /** dp */
    private int mMenuRightPadding = 50;
    /** 菜單寬度 */
    private int mMenuWidth;
    private int mHalfMenuWidth;
    private boolean once;

    public SlidingMenu(Context context, AttributeSet attrs) {
        super(context, attrs);
        mScreenWidth = ScreenUtils.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);
            // dp 轉 px
            mMenuRightPadding = (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);
    }

    @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();
        switch (action) {
            // ACTION_UP 時判斷:顯示區域大於菜單寬度一半則完全展開,否則收起
            case MotionEvent.ACTION_UP:
                int scrollX = getScrollX();
                if (scrollX > mHalfMenuWidth) {
                    this.smoothScrollTo(mMenuWidth, 0);
                } else {
                    this.smoothScrollTo(0, 0);
                }
                return true;
        }
        return super.onTouchEvent(ev);
    }
}

就這樣,完工。真正處理滑動的程式碼不到十行——說它簡單並不算誇張。程式碼太短就不逐行解釋了,看註解即可。

五、進階擴充

接下來把程式完善一下:把菜單改成 ListView 來證明沒有衝突、開放一個屬性讓開發者設定菜單距右邊的間距、再對外提供一個方法,讓使用者點擊按鈕時菜單自動滑出。

1. 加上自定義屬性

a、在 values 下新增 attr.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="SlidingMenu">
        <attr name="rightPadding" format="dimension" />
    </declare-styleable>
</resources>

b、在版面中宣告命名空間並使用屬性:

<com.example.zhy_slidingmenu.SlidingMenu
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    xmlns:zhy="https://schemas.android.com/apk/res/com.example.zhy_slidingmenu"
    android:layout_height="fill_parent"
    android:layout_width="wrap_content"
    android:scrollbars="none"
    zhy:rightPadding="100dp">
</com.example.zhy_slidingmenu.SlidingMenu>

命名空間的組成是 https://schemas.android.com/apk/res/ 加上自己的套件名稱;屬性寫法則是 zhy:rightPadding="100dp"。若沒有程式碼提示,先 clean 一下專案通常就會出現。

c、在自定義類別中透過三參數建構子取得屬性:

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_rightPadding:
                // 預設 50dp
                mMenuRightPadding = a.getDimensionPixelSize(attr,
                        (int) TypedValue.applyDimension(
                                TypedValue.COMPLEX_UNIT_DIP, 50f,
                                getResources().getDisplayMetrics()));
                break;
        }
    }
    a.recycle();
}

以後要增加更多自定義屬性,照同樣步驟補上即可。

2. 對外提供開啟菜單的方法

先用一個 isOpen 變數記錄菜單目前的狀態,並記得在 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;
/** 開啟菜單 */
public void openMenu() {
    if (isOpen) return;
    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();
    }
}

順手多加了兩個方法。主版面多放一顆按鈕來觸發 toggleMenu():

public class MainActivity extends Activity {

    private SlidingMenu mMenu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        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();
    }
}

把 padding 改成 100dp 後的效果,以及點擊按鈕的表現:

3. 用 ListView 驗證

ListView 也測試通過,大家可以依自己的需求自由調整。

另外,這次拿 QQ 當示範是因為下一步我想用這份程式碼改出與 QQ5.0 幾乎一致的效果——QQ 的菜單看起來像是藏在主畫面底下,而不是硬滑出來的,這個範例同樣做得到,值得期待;剩下的就是各種縮放與透明度動畫了。

源碼點擊下載

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