Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 監聽 ScrollView 滾動實現仿美團、大眾點評購買懸浮效果

編輯:Android 開發實例

最近在逛美團和大眾點評的 App 時,我注意到一個頗具匠心的交互效果,整體體驗既順暢又人性化,於是便饒有興致地自己動手實現了一遍。接下來就把完整的實現思路分享給大家。

如圖所示,當「立即搶購」布局向上滑動、觸及導航欄布局時,它會稳稳地貼在導航欄下方,而其他內容依然可以繼續滾動;而當我們向下滑動時,「立即搶購」布局又會隨著一起滑回來。乍看之下似乎有點複雜,但一旦點破思路,你便會豁然開朗。

實現思路

核心邏輯是這樣的:在向上滑動的過程中,我們持續判斷「立即搶購」布局是否已經滑到導航欄下方。一旦它的上邊緣頂到了導航欄,就新建一個「立即搶購」懸浮框顯示在導航欄下面,這樣便實現了懸浮粘頂的效果。而當我們向下滑動,等到「立即搶購」布局的下邊緣恰好回到剛才那個懸浮框的下邊緣時,就把懸浮框移除掉。有點拗口對吧?知道了思路,我們就來動手實現。

新建一個名為 MeiTuanDemo 的 Android 項目。先來看「立即搶購」(buy_layout.xml)的布局,這裡為了方便,我直接從美團上截了圖:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/buy_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/buy" />

</LinearLayout>

「立即搶購」布局搞定後,接下來編寫主界面布局。頂部是導航欄(同樣直接截自美團),下面依次是 ViewPager 布局、「立即搶購」布局以及其他內容,全部放進 ScrollView 里,界面結構還是相當清爽的:

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

    <ImageView
        android:id="@+id/imageView1"
        android:scaleType="centerCrop"
        android:layout_width="match_parent"
        android:layout_height="45dip"
        android:src="@drawable/navigation_bar" />

    <com.example.meituandemo.MyScrollView
        android:id="@+id/scrollView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

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

            <ImageView
                android:id="@+id/iamge"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/pic"
                android:scaleType="centerCrop" />

            <include
                android:id="@+id/buy"
                layout="@layout/buy_layout" />

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/one"
                android:scaleType="centerCrop" />

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/one"
                android:scaleType="centerCrop" />

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/one"
                android:scaleType="centerCrop" />
        </LinearLayout>
    </com.example.meituandemo.MyScrollView>

</LinearLayout>

你會發現主界面布局里用的並不是原生的 ScrollView,而是一個自定義的 MyScrollView。接下來就來看看它的內部實現。

自定義 MyScrollView

package com.example.meituandemo;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ScrollView;

public class MyScrollView extends ScrollView {

    private OnScrollListener onScrollListener;

    /**
     * 主要用在用戶手指離開後 MyScrollView 仍在繼續滑動時,
     * 用來保存 Y 的距離並做比較
     */
    private int lastScrollY;

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

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

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

    /**
     * 設置滾動監聽接口
     */
    public void setOnScrollListener(OnScrollListener onScrollListener) {
        this.onScrollListener = onScrollListener;
    }

    /**
     * 用戶手指離開時,用來獲取 MyScrollView 滾動的 Y 距離並回調給 onScroll
     */
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            int scrollY = MyScrollView.this.getScrollY();

            // 此時距離與記錄的距離不相等,隔 5 毫秒再給 handler 發送消息
            if (lastScrollY != scrollY) {
                lastScrollY = scrollY;
                handler.sendMessageDelayed(handler.obtainMessage(), 5);
            }
            if (onScrollListener != null) {
                onScrollListener.onScroll(scrollY);
            }
        };
    };

    /**
     * 重寫 onTouchEvent:手指在 MyScrollView 上時直接回調 Y 距離;
     * 手指抬起後 MyScrollView 可能仍在滑動,於是隔 5 毫秒給 handler 發消息繼續處理
     */
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (onScrollListener != null) {
            onScrollListener.onScroll(lastScrollY = this.getScrollY());
        }
        switch (ev.getAction()) {
            case MotionEvent.ACTION_UP:
                handler.sendMessageDelayed(handler.obtainMessage(), 5);
                break;
        }
        return super.onTouchEvent(ev);
    }

    /**
     * 滾動的回調接口
     */
    public interface OnScrollListener {
        /**
         * 回調方法,返回 MyScrollView 滑動的 Y 方向距離
         */
        public void onScroll(int scrollY);
    }
}

一看代碼你大概就明白了:核心就是對 ScrollView 的滾動 Y 值進行監聽。我們知道 ScrollView 本身並沒有提供滾動監聽,所以必須自己實現。最自然的想法是在 onTouchEvent() 里監聽 Y 軸變化,但問題在於——滑動時手指一旦離開 ScrollView,它往往還會因為慣性繼續滑動一段距離。因此我們選擇在用戶抬手後,每隔 5 毫秒判斷一次 ScrollView 是否已經停止滑動,並把最新的滾動 Y 值回調給 OnScrollListener 接口的 onScroll(int scrollY) 方法。這樣,外部只需調用 setOnScrollListener() 就能實時拿到滾動的 Y 值。

主界面 Activity 邏輯

實現了 Y 值監聽,剩下的就水到渠成——只需根據需要顯示或移除懸浮框。來看看 MainActivity 的代碼:

package com.example.meituandemo;

import android.app.Activity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.LinearLayout;

import com.example.meituandemo.MyScrollView.OnScrollListener;

public class MainActivity extends Activity implements OnScrollListener {

    private MyScrollView myScrollView;
    private LinearLayout mBuyLayout;
    private WindowManager mWindowManager;

    /** 手機屏幕寬度 */
    private int screenWidth;
    /** 懸浮框 View */
    private static View suspendView;
    /** 懸浮框的參數 */
    private static WindowManager.LayoutParams suspendLayoutParams;
    /** 購買布局的高度 */
    private int buyLayoutHeight;
    /** myScrollView 與其父布局的頂部距離 */
    private int myScrollViewTop;
    /** 購買布局與其父布局的頂部距離 */
    private int buyLayoutTop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myScrollView = (MyScrollView) findViewById(R.id.scrollView);
        mBuyLayout = (LinearLayout) findViewById(R.id.buy);

        myScrollView.setOnScrollListener(this);
        mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        screenWidth = mWindowManager.getDefaultDisplay().getWidth();
    }

    /**
     * 窗口獲得焦點(所有布局繪製完畢)時,獲取購買布局的高度與各頂部位置
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            buyLayoutHeight = mBuyLayout.getHeight();
            buyLayoutTop = mBuyLayout.getTop();
            myScrollViewTop = myScrollView.getTop();
        }
    }

    /**
     * 滾動 Y 距離大於等於購買布局頂部位置時顯示懸浮框;
     * 小於該位置時移除懸浮框
     */
    @Override
    public void onScroll(int scrollY) {
        if (scrollY >= buyLayoutTop) {
            if (suspendView == null) {
                showSuspend();
            }
        } else if (scrollY <= buyLayoutTop + buyLayoutHeight) {
            if (suspendView != null) {
                removeSuspend();
            }
        }
    }

    /**
     * 顯示購買懸浮框
     */
    private void showSuspend() {
        if (suspendView == null) {
            suspendView = LayoutInflater.from(this).inflate(R.layout.buy_layout, null);
            if (suspendLayoutParams == null) {
                suspendLayoutParams = new LayoutParams();
                suspendLayoutParams.type = LayoutParams.TYPE_PHONE;
                suspendLayoutParams.format = PixelFormat.RGBA_8888;
                suspendLayoutParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL
                        | LayoutParams.FLAG_NOT_FOCUSABLE;
                suspendLayoutParams.gravity = Gravity.TOP;
                suspendLayoutParams.width = screenWidth;
                suspendLayoutParams.height = buyLayoutHeight;
                suspendLayoutParams.x = 0;
                suspendLayoutParams.y = myScrollViewTop;
            }
        }
        mWindowManager.addView(suspendView, suspendLayoutParams);
    }

    /**
     * 移除購買懸浮框
     */
    private void removeSuspend() {
        if (suspendView != null) {
            mWindowManager.removeView(suspendView);
            suspendView = null;
        }
    }
}

上面的代碼並不複雜,本質就是根據 ScrollView 滑動的距離來判斷顯示還是移除懸浮框。懸浮框的實現主要依靠 WindowManager 這個類:調用它的 addView 方法添加懸浮框,調用 removeView 移除懸浮框。

通過上述代碼,就實現了美團、大眾點評那種懸浮粘頂的效果。需要注意的是,在運行項目之前,必須在 AndroidManifest.xml 中加入懸浮窗權限:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

一切就緒,運行項目來看看實際效果吧。

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