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

Android 上下菜單雙向滑動菜單的完整實現

編輯:關於 Android 程式設計

借鑒了網上前輩們左右滑動側邊欄的思路,我把它改造成了上下方向的雙向滑動特效。核心原理並不複雜:根據手指滑動的方向,動態顯示或隱藏上方與下方的菜單布局。整個實現主要依賴 onTouch 方法,通過實時獲取滑動距離來做偏移計算。下面把完整代碼分享出來,註釋寫得比較詳細,感興趣的朋友可以細細研究。

import android.content.Context;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.widget.RelativeLayout;

public class UpAndDownSlidinglayout extends RelativeLayout implements OnTouchListener {
    /** 滾動顯示和隱藏上側布局時,手指滑動需要達到的速度 */
    public static final int SNAP_VELOCITY = 200;
    /** 滑動狀態:未進行任何滑動 */
    public static final int DO_NOTHING = 0;
    /** 滑動狀態:正在滑出上側菜單 */
    public static final int SHOW_UP_MENU = 1;
    /** 滑動狀態:正在滑出下側菜單 */
    public static final int SHOW_DOWN_MENU = 2;
    /** 滑動狀態:正在隱藏上側菜單 */
    public static final int HIDE_UP_MENU = 3;
    /** 滑動狀態:正在隱藏下側菜單 */
    public static final int HIDE_DOWN_MENU = 4;

    private int slideState;          // 記錄當前的滑動狀態
    private int screenWidth;         // 屏幕寬度值
    private int screenHeight;
    private int touchSlop;           // 在被判定為滾動之前用戶手指可以移動的最大值
    private float xDown;             // 記錄手指按下時的橫坐標
    private float yDown;             // 記錄手指按下時的縱坐標
    private float xMove;             // 記錄手指移動時的橫坐標
    private float yMove;             // 記錄手指移動時的縱坐標
    private float yUp;               // 記錄手機抬起時的縱坐標
    private boolean isUpMenuVisible;   // 上側菜單當前是顯示還是隱藏
    private boolean isDownMenuVisible; // 下側菜單當前是顯示還是隱藏
    private boolean isSliding;         // 是否正在滑動
    private View upMenuLayout;         // 上側菜單布局對象
    private View downMenuLayout;       // 下側菜單布局對象
    private View contentLayout;        // 內容布局對象
    private View mBindView;            // 用於監聽滑動事件的 View
    private MarginLayoutParams upMenuLayoutParams;      // 上側菜單布局的參數
    private MarginLayoutParams downMenuLayoutParams;    // 下側菜單布局的參數
    private RelativeLayout.LayoutParams contentLayoutParams; // 內容布局的參數
    private VelocityTracker mVelocityTracker;           // 用於計算手指滑動的速度

    public UpAndDownSlidinglayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        screenWidth = wm.getDefaultDisplay().getWidth();
        screenHeight = wm.getDefaultDisplay().getHeight();
        touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    /** 綁定監聽滑動事件的 View */
    public void setScrollEvent(View bindView) {
        mBindView = bindView;
        mBindView.setOnTouchListener(this);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        createVelocityTracker(event);
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // 手指按下時,記錄按下時的坐標
                xDown = event.getRawX();
                yDown = event.getRawY();
                slideState = DO_NOTHING;
                break;
            case MotionEvent.ACTION_MOVE:
                xMove = event.getRawX();
                yMove = event.getRawY();
                int moveDistanceX = (int) (xMove - xDown);
                int moveDistanceY = (int) (yMove - yDown);
                checkSlideState(moveDistanceX, moveDistanceY);
                switch (slideState) {
                    case SHOW_UP_MENU:
                        contentLayoutParams.bottomMargin = -moveDistanceY;
                        checkUpMenuBorder();
                        contentLayout.setLayoutParams(contentLayoutParams);
                        break;
                    case HIDE_UP_MENU:
                        contentLayoutParams.bottomMargin = -upMenuLayoutParams.height - moveDistanceY;
                        checkUpMenuBorder();
                        contentLayout.setLayoutParams(contentLayoutParams);
                    case SHOW_DOWN_MENU:
                        contentLayoutParams.topMargin = moveDistanceY;
                        checkDownMenuBorder();
                        contentLayout.setLayoutParams(contentLayoutParams);
                        break;
                    case HIDE_DOWN_MENU:
                        contentLayoutParams.topMargin = -downMenuLayoutParams.height + moveDistanceY;
                        checkDownMenuBorder();
                        contentLayout.setLayoutParams(contentLayoutParams);
                    default:
                        break;
                }
                break;
            case MotionEvent.ACTION_UP:
                yUp = event.getRawY();
                int upDistanceY = (int) (yUp - yDown);
                if (isSliding) {
                    // 手指抬起時,判斷當前手勢的意圖
                    switch (slideState) {
                        case SHOW_UP_MENU:
                            if (shouldScrollToUpMenu()) { scrollToUpMenu(); } else { scrollToContentFromUpMenu(); }
                            break;
                        case HIDE_UP_MENU:
                            if (shouldScrollToContentFromUpMenu()) { scrollToContentFromUpMenu(); } else { scrollToUpMenu(); }
                            break;
                        case SHOW_DOWN_MENU:
                            if (shouldScrollToDownMenu()) { scrollToDownMenu(); } else { scrollToContentFromDownMenu(); }
                            break;
                        case HIDE_DOWN_MENU:
                            if (shouldScrollToContentFromDownMenu()) { scrollToContentFromDownMenu(); } else { scrollToDownMenu(); }
                            break;
                        default:
                            break;
                    }
                } else if (upDistanceY < touchSlop && isUpMenuVisible) {
                    // 上側菜單顯示時,點擊內容部分直接滾動到內容界面
                    scrollToContentFromUpMenu();
                } else if (upDistanceY < touchSlop && isDownMenuVisible) {
                    // 下側菜單顯示時,點擊內容部分直接滾動到內容界面
                    scrollToContentFromDownMenu();
                }
                recycleVelocityTracker();
                break;
        }
        return true;
    }

    /** 創建 VelocityTracker 對象,並將觸摸事件加入到其中 */
    private void createVelocityTracker(MotionEvent event) {
        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.addMovement(event);
    }

    /** 根據手指移動的距離,判斷用戶的滑動意圖,並給 slideState 賦值 */
    private void checkSlideState(int moveDistanceX, int moveDistanceY) {
        if (isUpMenuVisible) {
            if (!isSliding && Math.abs(moveDistanceY) >= touchSlop && moveDistanceY < 0) {
                isSliding = true;
                slideState = HIDE_UP_MENU;
            }
        } else if (isDownMenuVisible) {
            if (!isSliding && Math.abs(moveDistanceY) >= touchSlop && moveDistanceY > 0) {
                isSliding = true;
                slideState = HIDE_DOWN_MENU;
            }
        } else {
            if (!isSliding && Math.abs(moveDistanceY) >= touchSlop && moveDistanceY > 0 && Math.abs(moveDistanceX) < touchSlop) {
                isSliding = true;
                slideState = SHOW_UP_MENU;
                contentLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
                contentLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                contentLayout.setLayoutParams(contentLayoutParams);
                // 用戶想滑動上側菜單,顯示上側菜單,隱藏下側菜單
                upMenuLayout.setVisibility(View.VISIBLE);
                downMenuLayout.setVisibility(View.GONE);
            } else if (!isSliding && Math.abs(moveDistanceY) >= touchSlop && moveDistanceY < 0 && Math.abs(moveDistanceX) < touchSlop) {
                isSliding = true;
                slideState = SHOW_DOWN_MENU;
                contentLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 0);
                contentLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
                contentLayout.setLayoutParams(contentLayoutParams);
                // 用戶想滑動下側菜單,顯示下側菜單,隱藏上側菜單
                upMenuLayout.setVisibility(View.GONE);
                downMenuLayout.setVisibility(View.VISIBLE);
            }
        }
    }

    /** 檢查上側菜單的邊界值,防止綁定布局滑出屏幕 */
    private void checkUpMenuBorder() {
        if (contentLayoutParams.bottomMargin > 0) {
            contentLayoutParams.bottomMargin = 0;
        } else if (contentLayoutParams.bottomMargin < -upMenuLayoutParams.height) {
            contentLayoutParams.bottomMargin = -upMenuLayoutParams.height;
        }
    }

    /** 檢查下側菜單的邊界值,防止綁定布局滑出屏幕 */
    private void checkDownMenuBorder() {
        if (contentLayoutParams.topMargin > 0) {
            contentLayoutParams.topMargin = 0;
        } else if (contentLayoutParams.topMargin < -downMenuLayoutParams.height) {
            contentLayoutParams.topMargin = -downMenuLayoutParams.height;
        }
    }

    /** 判斷是否應該展示上側菜單:移動距離大於菜單高度 1/2,或速度大於 SNAP_VELOCITY */
    private boolean shouldScrollToUpMenu() {
        return yUp - yDown > upMenuLayoutParams.height / 2 || getScrollVelocity() > SNAP_VELOCITY;
    }

    /** 判斷是否應該展示下側菜單 */
    private boolean shouldScrollToDownMenu() {
        return yDown - yUp > downMenuLayoutParams.height / 2 || getScrollVelocity() > SNAP_VELOCITY;
    }

    /** 判斷是否應該從上側菜單滾動到內容布局 */
    private boolean shouldScrollToContentFromUpMenu() {
        return yDown - yUp > upMenuLayoutParams.height / 2 || getScrollVelocity() > SNAP_VELOCITY;
    }

    /** 判斷是否應該從下側菜單滾動到內容布局 */
    private boolean shouldScrollToContentFromDownMenu() {
        return yUp - yDown > downMenuLayoutParams.height / 2 || getScrollVelocity() > SNAP_VELOCITY;
    }

    /** 獲取手指在綁定布局上的滑動速度,單位為每秒移動的像素值 */
    private int getScrollVelocity() {
        mVelocityTracker.computeCurrentVelocity(1000);
        int velocity = (int) mVelocityTracker.getXVelocity();
        return Math.abs(velocity);
    }

    class UpMenuScrollTask extends AsyncTask<Integer, Integer, Integer> {
        @Override
        protected Integer doInBackground(Integer... speed) {
            int bottomMargin = contentLayoutParams.bottomMargin;
            // 根據傳入的速度滾動界面,到達邊界值時跳出循環
            while (true) {
                bottomMargin = bottomMargin + speed[0];
                if (bottomMargin < -upMenuLayoutParams.height) { bottomMargin = -upMenuLayoutParams.height; break; }
                if (bottomMargin > 0) { bottomMargin = 0; break; }
                publishProgress(bottomMargin);
                sleep(15); // 每次循環睡眠一段時間,肉眼才能看到滾動動畫
            }
            if (speed[0] > 0) { isUpMenuVisible = false; } else { isUpMenuVisible = true; }
            isSliding = false;
            return bottomMargin;
        }
        @Override
        protected void onProgressUpdate(Integer... bottomMargin) {
            contentLayoutParams.bottomMargin = bottomMargin[0];
            contentLayout.setLayoutParams(contentLayoutParams);
            unFocusBindView();
        }
        @Override
        protected void onPostExecute(Integer bottomMargin) {
            contentLayoutParams.bottomMargin = bottomMargin;
            contentLayout.setLayoutParams(contentLayoutParams);
        }
    }

    class DownMenuScrollTask extends AsyncTask<Integer, Integer, Integer> {
        @Override
        protected Integer doInBackground(Integer... speed) {
            int topMargin = contentLayoutParams.topMargin;
            while (true) {
                topMargin = topMargin + speed[0];
                if (topMargin < -downMenuLayoutParams.height) { topMargin = -downMenuLayoutParams.height; break; }
                if (topMargin > 0) { topMargin = 0; break; }
                publishProgress(topMargin);
                sleep(15);
            }
            if (speed[0] > 0) { isDownMenuVisible = false; } else { isDownMenuVisible = true; }
            isSliding = false;
            return topMargin;
        }
        @Override
        protected void onProgressUpdate(Integer... topMargin) {
            contentLayoutParams.topMargin = topMargin[0];
            contentLayout.setLayoutParams(contentLayoutParams);
            unFocusBindView();
        }
        @Override
        protected void onPostExecute(Integer topMargin) {
            contentLayoutParams.topMargin = topMargin;
            contentLayout.setLayoutParams(contentLayoutParams);
        }
    }

    /** 使當前線程睡眠指定的毫秒數 */
    private void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /** 使可獲得焦點的控件在滑動時失去焦點 */
    private void unFocusBindView() {
        if (mBindView != null) {
            mBindView.setPressed(false);
            mBindView.setFocusable(false);
            mBindView.setFocusableInTouchMode(false);
        }
    }

    public void scrollToUpMenu() { new UpMenuScrollTask().execute(-30); }
    public void scrollToDownMenu() { new DownMenuScrollTask().execute(-30); }
    public void scrollToContentFromUpMenu() { new UpMenuScrollTask().execute(30); }
    public void scrollToContentFromDownMenu() { new DownMenuScrollTask().execute(30); }
    public boolean isUpLayoutVisible() { return isUpMenuVisible; }
    public boolean isDownLayoutVisible() { return isDownMenuVisible; }

    /** 在 onLayout 中重新設定上側菜單、下側菜單、以及內容布局的參數 */
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (changed) {
            upMenuLayout = getChildAt(0);
            upMenuLayoutParams = (MarginLayoutParams) upMenuLayout.getLayoutParams();
            downMenuLayout = getChildAt(1);
            downMenuLayoutParams = (MarginLayoutParams) downMenuLayout.getLayoutParams();
            contentLayout = getChildAt(2);
            contentLayoutParams = (RelativeLayout.LayoutParams) contentLayout.getLayoutParams();
            contentLayoutParams.height = screenHeight;
            contentLayout.setLayoutParams(contentLayoutParams);
        }
    }

    private void recycleVelocityTracker() {
        mVelocityTracker.recycle();
        mVelocityTracker = null;
    }
}

使用示例

下面是一個簡單的 Activity,用 ListView 填充內容布局,並綁定滑動事件:

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.app.Activity;

/** 滑動菜單 Demo 主 Activity */
public class MainActivity2 extends Activity {
    private UpAndDownSlidinglayout updownSldingLayout; // 雙向滑動菜單布局
    private ListView contentList;                      // 內容布局上的 ListView
    private LinearLayout ll;
    private ArrayAdapter<String> contentListAdapter;   // ListView 的適配器

    private String[] contentItems = {
        "Content Item 1", "Content Item 2", "Content Item 3", "Content Item 4",
        "Content Item 5", "Content Item 6", "Content Item 7", "Content Item 8",
        "Content Item 9", "Content Item 10", "Content Item 11", "Content Item 12",
        "Content Item 13", "Content Item 14", "Content Item 15", "Content Item 16"
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        ll = (LinearLayout) findViewById(R.id.content);
        updownSldingLayout = (UpAndDownSlidinglayout) findViewById(R.id.updown_sliding_layout);
        contentList = (ListView) findViewById(R.id.contentList);
        contentListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, contentItems);
        contentList.setAdapter(contentListAdapter);
        updownSldingLayout.setScrollEvent(ll);
    }
}

布局文件

布局中依次放置上側菜單、下側菜單和內容區域三個子布局:

<com.example.UpAndDownSlidinglayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/updown_sliding_layout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <RelativeLayout
        android:id="@+id/up_menu"
        android:layout_width="fill_parent"
        android:layout_height="300dp"
        android:layout_alignParentTop="true"
        android:background="#00ccff"
        android:visibility="invisible" >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="This is up menu"
            android:textColor="#000000"
            android:textSize="28sp" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/down_menu"
        android:layout_width="fill_parent"
        android:layout_height="300dp"
        android:layout_alignParentBottom="true"
        android:background="#00ffcc"
        android:visibility="invisible" >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="This is down menu"
            android:textColor="#000000"
            android:textSize="28sp" />
    </RelativeLayout>

    <LinearLayout
        android:id="@+id/content"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:background="#e9e9e9" >
        <ListView
            android:id="@+id/contentList"
            android:layout_width="fill_parent"
            android:layout_height="500dp"
            android:scrollbars="none"
            android:cacheColorHint="#00000000" >
        </ListView>
    </LinearLayout>
</com.example.UpAndDownSlidinglayout>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved