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

Android 監聽 ScrollView 滾動:打造美團、大眾點評式購買懸浮效果(優化版)

編輯:Android 開發實例

早前我曾寫過一篇關於美團、大眾點評購買框懸浮效果的文章,但自己回頭看時總覺得並不夠理想。當手指快速滑動界面時,懸浮框出現的瞬間會有一卡一卡的感覺,還有的朋友反映偶爾會同時冒出兩個布局。這些問題的根源,在於我当时選擇用 Handler 去間接獲取 ScrollView 的 Y 軸偏移量,走了不少彎路。

後來有朋友推薦了 Scrolling Tricks 這個方案,我下載試用後確實發現美團、大眾點評採用的正是這套思路,可惜它只能在 API 11 及以上版本運行,對需要兼容舊版本的項目來說略有遺憾。於是我在它的基礎上做了改進,並把完整的實現思路整理出來分享給大家。整體思路其實並不複雜,關鍵在於直接監聽 ScrollView 的滾動。

一、自定義 ScrollView 並直接監聽滾動

最直接的做法是重寫 onScrollChanged() 方法,在這個方法里就能拿到實時的滾動 Y 值,完全不需要再借助 Handler。先來看看自定義的 MyScrollView:

package com.example.meituandemo;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ScrollView;

/**
 * 自定義 ScrollView,提供滾動監聽能力
 */
public class MyScrollView extends ScrollView {

    private OnScrollListener onScrollListener;

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

    @Override
    public int computeVerticalScrollRange() {
        return super.computeVerticalScrollRange();
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        if (onScrollListener != null) {
            onScrollListener.onScroll(t);
        }
    }

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

二、主界面布局設計

布局的關鍵之處在於:我們在 ScrollView 內部預先放置了一份購買布局,同時又在頂部準備了一份一模一樣的購買布局。這兩份布局會通過後續代碼實現精準重合。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/parent_layout"
    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">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <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>

            <include
                android:id="@+id/top_buy_layout"
                layout="@layout/buy_layout" />
        </FrameLayout>
    </com.example.meituandemo.MyScrollView>

</LinearLayout>

看到這裡你也許會想:先把頂部的購買布局隱藏,等下面的布局滑上來再顯示它,不就行了?如果真這麼做,效果就和之前那篇文章沒什麼區別了。這個優化版採用的顯然不是這種笨辦法,我們直接看主界面代碼。

三、核心邏輯:讓兩份布局重合

package com.example.meituandemo;

import android.app.Activity;
import android.os.Bundle;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.LinearLayout;

import com.example.meituandemo.MyScrollView.OnScrollListener;

public class MainActivity extends Activity implements OnScrollListener {

    /** 自定義的 MyScrollView */
    private MyScrollView myScrollView;
    /** MyScrollView 裡面的購買布局 */
    private LinearLayout mBuyLayout;
    /** 位於頂部的購買布局 */
    private LinearLayout mTopBuyLayout;

    @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);
        mTopBuyLayout = (LinearLayout) findViewById(R.id.top_buy_layout);

        myScrollView.setOnScrollListener(this);

        // 當布局狀態或控件可見性發生改變時回調的接口
        findViewById(R.id.parent_layout).getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                // 這一步很重要,使得頂部的購買布局與下方的購買布局重合
                onScroll(myScrollView.getScrollY());
            }
        });
    }

    @Override
    public void onScroll(int scrollY) {
        int mBuyLayout2ParentTop = Math.max(scrollY, mBuyLayout.getTop());
        mTopBuyLayout.layout(0, mBuyLayout2ParentTop, mTopBuyLayout.getWidth(), mBuyLayout2ParentTop + mTopBuyLayout.getHeight());
    }
}

四、原理講解

界面邏輯只有寥寥幾行,但初次接觸的朋友可能還是不太明白它究竟是如何做到的。這裡我詳細說明一下。

核心在於,我們讓頂部的購買布局與下方的購買布局完全重合起來。layout() 方法的作用是確定一個 View 的大小與位置,並將它繪製出來,傳入的四個參數分別是這個 View 四個頂點的坐標。要特別注意的是,這裡的坐標並不是相對於屏幕原點,而是相對於它的父布局而言的。

我們在主頁面最外層的 ViewGroup 上添加了一個布局狀態改變的監聽器。當屏幕繪製完成後,會回調到 onGlobalLayout() 方法,我們在其中手動調用了一次 onScroll()。此時 myScrollView.getScrollY() 等於 0,因此當 scrollY 小於 mBuyLayout.getTop() 時,頂部購買布局的上邊緣到 MyScrollView 上邊緣的距離,就等於 mBuyLayout.getTop()(也就是下方布局上邊緣到 MyScrollView 上邊緣的距離)。這一刻,頂部購買布局與下方購買布局恰好重合。

而當 MyScrollView 向上滾動時,頂部購買布局的上邊緣始終要和 MyScrollView 的上邊緣保持 mBuyLayout.getTop() 這個距離,所以它自然就跟著向上移動。一旦 scrollY 大於 mBuyLayout.getTop(),就代表購買布局的上邊緣已經滑到了導航欄位置,此時購買布局的上邊緣便改為始終與 MyScrollView 的上邊緣保持 scrollY 這個距離——於是購買布局就一直「粘」在導航欄下方,不會再隨內容滾走。

當然,你也可以選擇用一個懸浮框一開始就覆蓋在下方的購買布局之上,然後在 onScroll() 里不断更新懸浮框的位置。只不過要留意,懸浮框的 x、y 坐標並不是相對於父布局的,這一點需要格外小心。這種做法雖然也能實現效果,但相對複雜得多。因此遇到類似需求時,直接用上面這套方案就好,簡潔明瞭。

運行程序你會發現,無論怎麼滑動都不會再出現卡頓或雙布局的情況,流暢度與美團、大眾點評的實際效果基本一致。優化版的講解到這裡就結束了。

原文轉自:https://blog.csdn.net/xiaanming/article/details/17761431

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