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

監聽 ScrollView 滾動實現懸浮吸頂效果:重現美團、大眾點評的購買欄

編輯:關於 Android 程式設計

行動裝置幾乎成了每個人的隨身配備,而決定一個 App 好不好的,除了功能本身,使用者體驗與介面細節往往才是關鍵。最近在美團與大眾點評上看到一個很貼心的設計:往下滑動時,「立即搶購」那一欄會自動吸附在頂部導航列下方,隨時都能下單;往回滑動時它又乖乖回到原本的位置。這種吸頂效果自己動手做過一次,就會發現思路比想像中簡單。

先想清楚原理

觀察上面第二張圖:當「立即搶購」區塊向上滑到導航列下方時,它就貼在那裡不動,而底下的內容仍可繼續滾動;反向滑動時,它又跟著一起往下走。

拆解之後只有兩個動作:

  1. 向上滑動時,持續判斷「立即搶購」的上緣是否已經頂到導航列。一旦貼上,就在導航列下方建立一個懸浮層顯示同樣的內容,視覺上就變成吸頂。
  2. 向下滑動時,當原本的「立即搶購」區塊下緣退回到懸浮層底部以下,就移除懸浮層,讓畫面回復原狀。

於是問題變成:怎麼即時取得 ScrollView 的滾動距離?遺憾的是 ScrollView 本身並未提供滾動監聽,這部分必須自己補上。

Step 1:立即搶購的佈局

為了示範方便,這裡直接用截圖當內容:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

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

Step 2:主界面佈局

上方是導航列,下方是 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:layout_width="match_parent"
        android:layout_height="45dip"
        android:scaleType="centerCrop"
        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 ... />
            <ImageView ... />
            <ImageView ... />
        </LinearLayout>
    </com.example.meituandemo.MyScrollView>
</LinearLayout>

注意最外層的捲動容器不是 ScrollView,而是自訂的 MyScrollView。

Step 3:自訂 MyScrollView

public class MyScrollView extends ScrollView {

    private OnScrollListener onScrollListener;

    /** 用於手指離開後,持續追蹤 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;
    }

    /** 手指離開後,每隔 5ms 檢查滾動是否已停止 */
    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int scrollY = MyScrollView.this.getScrollY();
            if (lastScrollY != scrollY) {
                lastScrollY = scrollY;
                handler.sendMessageDelayed(handler.obtainMessage(), 5);
            }
            if (onScrollListener != null) {
                onScrollListener.onScroll(scrollY);
            }
        }
    };

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (onScrollListener != null) {
            onScrollListener.onScroll(lastScrollY = getScrollY());
        }
        switch (ev.getAction()) {
            case MotionEvent.ACTION_UP:
                // 抬手後可能還在滑,交給 handler 持續追蹤
                handler.sendMessageDelayed(handler.obtainMessage(), 5);
                break;
            default:
                break;
        }
        return super.onTouchEvent(ev);
    }

    public interface OnScrollListener {
        void onScroll(int scrollY);
    }
}

這段程式的巧妙之處在於處理了「手指離開但畫面仍在滑」的情況。如果只在 onTouchEvent() 中監聽,使用者一抬手就再也收不到滾動事件,吸頂時機自然會錯。因此 ACTION_UP 時額外丟一個延遲訊息給 Handler,讓它每 5 毫秒比對一次 getScrollY():數值還在變就繼續排下一輪,不再變動就停止。

對外只需要呼叫 setOnScrollListener(),就能持續收到滾動距離。

Step 4:Activity 中的顯示與移除邏輯

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();
        }
    }

    @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 WindowManager.LayoutParams();
                suspendLayoutParams.type = WindowManager.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;
        }
    }
}

整個判斷只有兩條界線:buyLayoutTop 是懸浮層該出現的門檻,buyLayoutTop + buyLayoutHeight 是它該消失的位置。而懸浮層的實作完全是靠 WindowManager——addView() 加一個浮在上方的 View,removeView() 把它移掉。

別忘了在 AndroidManifest.xml 加上權限:

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

執行結果如下:

這個做法的限制與改良方向

上述实现能跑、思路也清楚,但用在正式專案前,有幾個地方值得重新評估:

  • TYPE_PHONE 已不適用。從 Android 8.0 起,這類懸浮層必須改用 TYPE_APPLICATION_OVERLAY,且 SYSTEM_ALERT_WINDOW 需引導使用者到系統設定手動授予「顯示在其他應用程式上層」權限,單純在 Manifest 宣告已不足夠。
  • WindowManager 是全局層級的。用來做頁面內部的吸頂其實偏重,且與 Activity 生命週期脫鉤時容易殘留視圖。更合適的做法是直接在 Activity 佈局中預先放一個 include 出來的懸浮 View,一開始設為 INVISIBLE,需要時切換可見性並做 translation 動畫。
  • 用 CoordinatorLayout 更省事。若使用新版 Support Library,CoordinatorLayout 搭配 AppBarLayout 與 CollapsingToolbarLayout 就能原生實現吸頂與收合,不必自己算座標。
  • NestedScrollView 有內建監聽。它提供 setOnScrollChangeListener(),省掉自訂 ScrollView 的功夫,且能與 RecyclerView 等巢狀捲動元件協同運作。
  • 位置數值要在版面完成後才取得。在 onCreate() 中呼叫 getHeight() 一律回傳 0,這是很多人卡住的地方;本例用 onWindowFocusChanged(),實務上也可以改用 ViewTreeObserver 或 doOnLayout。

理解「監聽滾動距離 → 與門檻比較 → 顯示或移除覆蓋層」這個骨架之後,無論是自己實作還是改用官方元件,都能快速做出流暢自然的吸頂效果。

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