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

自定義 ScrollView 監聽滑動距離,打造仿 QQ 空間的漸變標題欄

編輯:關於 Android 程式設計

從一個再熟悉不過的滾動視圖說起

做 Android 開發,ScrollView 幾乎是必備控件。它分橫向(HorizontalScrollView)與縱向(ScrollView)兩種,日常我們用得最多的是縱向那一種。功能雖強,卻總有設計師能畫出它撐不住的稿子——這時候,自定義就是唯一的出路。

本文要動手的,是一個很經典的需求:頂部大圖向上滾動時,標題欄由全透明漸變為實心色塊,文字也同步淡入。QQ 空間、網易新聞都是這個套路。先看一眼成品:

幾個容易被忽略的 ScrollView 屬性

動手之前,順手整理一批不常用但偶爾能救命的屬性:

  • android:scrollbars:控制滾動條的顯示方式,可取 none(隱藏)、horizontal(水平)、vertical(垂直)。
  • android:scrollbarStyle:滾動條的風格與位置,可選 insideOverlay、insideInset、outsideOverlay、outsideInset。
  • android:scrollbarThumbHorizontal:自定義水平滾動條的 drawable。
  • android:soundEffectsEnabled:觸摸時是否播放音效。
  • android:fadingEdge:拖動時邊緣漸隱的方向,none 表示不變色,horizontal / vertical 分別對應水平與垂直方向變淡。
  • android:fadingEdgeLength:配合上一條使用,指定漸隱區域的長度。
  • android:scrollX / android:scrollY:以像素為單位設定水平/垂直方向的滾動偏移量。
  • android:scrollbarAlwaysDrawHorizontalTrack:是否始終繪製滾動條軌道。
  • android:scrollbarDefaultDelayBeforeFade:互動結束後多少毫秒開始淡出。

這些屬性瞭解即可,真正要解決問題,靠的是滑動監聽。

ScrollView 的滑動監聽:onScrollChanged

遺憾的是,Google 並沒有為 ScrollView 提供「當前滑動距離」「是否到達頂部/底部」這類現成方法,只留了一個 protected 的 onScrollChanged:

@Override
protected void onScrollChanged(int x, int y, int oldx, int oldy) {
    super.onScrollChanged(x, y, oldx, oldy);
    // 在這裡做我們想做的事
}

翻一下源碼註釋,四個參數含義非常直白:

/**
 * This is called in response to an internal scroll in this view
 * (i.e., the view scrolled its own contents). This is typically as a result of
 * scrollBy(int, int) or scrollTo(int, int) having been called.
 *
 * @param l   Current horizontal scroll origin.
 * @param t   Current vertical scroll origin.
 * @param oldl Previous horizontal scroll origin.
 * @param oldt Previous vertical scroll origin.
 */

也就是:l 為當前橫向偏移、t 為當前縱向偏移、oldl 與 oldt 是上一次的對應值。

問題在於,這個方法是 protected,外部拿不到。解決思路有兩條:定義一個繼承自 ScrollView 的自定義控件,把方法「暴露出來」;或者乾脆在自定義 View 裡重寫它並提供接口。

第一步:封裝帶監聽的 GradationScrollView

package com.hankkin.gradationscroll;

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

/**
 * 帶滾動監聽的 ScrollView
 */
public class GradationScrollView extends ScrollView {

    public interface ScrollViewListener {
        void onScrollChanged(GradationScrollView scrollView, int x, int y, int oldx, int oldy);
    }

    private ScrollViewListener scrollViewListener = null;

    public GradationScrollView(Context context) {
        super(context);
    }

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

    public GradationScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setScrollViewListener(ScrollViewListener scrollViewListener) {
        this.scrollViewListener = scrollViewListener;
    }

    @Override
    protected void onScrollChanged(int x, int y, int oldx, int oldy) {
        super.onScrollChanged(x, y, oldx, oldy);
        if (scrollViewListener != null) {
            scrollViewListener.onScrollChanged(this, x, y, oldx, oldy);
        }
    }
}

本質上就是一個「轉發器」:系統回調 onScrollChanged,我們再把它拋給外部的 ScrollViewListener。此後任何界面都能拿到實時的縱向偏移量 y。

第二步:搭出布局骨架

結構很簡單——自定義 ScrollView 包住一張頭圖和一個不可滑動的 ListView,再在最上層疊一個 TextView 當標題欄(想放複雜內容,換成布局文件即可)。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.hankkin.gradationtitlebar.QQSpeakActivity">

    <com.hankkin.gradationscroll.GradationScrollView
        android:id="@+id/scrollview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="none">

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

            <ImageView
                android:id="@+id/iv_banner"
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:scaleType="fitXY"
                android:src="@drawable/banner3" />

            <com.hankkin.gradationscroll.NoScrollListview
                android:id="@+id/listview"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>
    </com.hankkin.gradationscroll.GradationScrollView>

    <TextView
        android:id="@+id/textview"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:background="#00000000"
        android:gravity="center|bottom"
        android:paddingBottom="10dp"
        android:text="我是標題"
        android:textColor="@color/transparent"
        android:textSize="18sp" />
</RelativeLayout>

關鍵細節有兩個:標題欄初始背景設為全透明(#00000000),文字顏色也先透明;ScrollView 的 scrollbars 關掉,視覺更乾淨。

第三步:讓透明度跟著滾動距離走

漸變的「刻度尺」是頭圖高度。所以要先等布局測量完成,拿到 ImageView 的實際高度,再掛上監聽。

/**
 * 獲取頂部圖片高度後,設置滾動監聽
 */
private void initListeners() {
    ViewTreeObserver vto = ivBanner.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            textView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            height = ivBanner.getHeight();
            scrollView.setScrollViewListener(QQSpeakActivity.this);
        }
    });
}

監聽回調裡只需要一個比例:當前滾動距離除以頭圖高度,再乘以 255 得到 alpha。分三種情況處理即可。

/**
 * 滑動監聽
 */
@Override
public void onScrollChanged(GradationScrollView scrollView, int x, int y, int oldx, int oldy) {
    if (y <= 0) {
        // 還在頂部,標題完全透明
        textView.setBackgroundColor(Color.argb(0, 144, 151, 166));
    } else if (y <= height) {
        // 滾動距離小於 banner 高度,背景與文字同步漸變
        float scale = (float) y / height;
        float alpha = 255 * scale;
        textView.setTextColor(Color.argb((int) alpha, 255, 255, 255));
        textView.setBackgroundColor(Color.argb((int) alpha, 144, 151, 166));
    } else {
        // 已滾過 banner,恢復為不透明的實心標題欄
        textView.setBackgroundColor(Color.argb(255, 144, 151, 166));
    }
}

到這裡,效果就出來了。

小結

整個方案的核心只有一句話:把 ScrollView 的 onScrollChanged 暴露出來,再用滾動距離與頭圖高度的比值去驅動 alpha。難度並不高,卡住我們的往往只是「沒動手」。

理解了這個模型,後續想加縮放、加視差、加插值動畫,都只是在同一個回調裡換公式而已。

完整源碼:https://github.com/Hankkin/GradationTitleBar(項目裡另附帶 banner 的版本,原理一致。)

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