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

Android 頂部吸附視圖(Sticky Header)實作詳解

編輯:關於 Android 程式設計

不知從什麼時候開始,這種效果在 UI 設計中流行了起來。先來看看效果:

在支付寶、美團等許多 App 中都能看到它的身影。要實現這個效果,我們可以分析一下思路:

我們需要用到兩個一模一樣的版面配置來顯示吸附效果——一個是正常隨滾動移動的,另一個是滑到頂部後固定不動的。正常的那個隨著 ScrollView 一起滾動,滾到哪算哪;當它滾到最上方的時候,我們就把吸附版面的那個放到頂部,而正常的內容其實還在後面繼續滾。理清這個邏輯後,我們來看看具體如何實作。

一、版面配置

先來看吸附用的版面,這裡只用幾張圖片稍作示意。

吸附版面(stick_layout.xml):

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="50dp"
    android:orientation="horizontal" >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textColor="#FFFFFF"
        android:background="#232323"
        android:text="我不會動"
        android:textSize="30dp" />
</LinearLayout>

主版面(activity_main.xml):

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/parent_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <com.xys.scrolltrick.TrickScroll
        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="200dp"
                    android:background="@drawable/ic_launcher"
                    android:scaleType="centerCrop" />
                <include android:id="@+id/stick" layout="@layout/stick_layout" />
                <ImageView
                    android:layout_width="match_parent"
                    android:layout_height="200dp"
                    android:background="@drawable/ic_launcher"
                    android:scaleType="centerCrop" />
                <ImageView
                    android:layout_width="match_parent"
                    android:layout_height="200dp"
                    android:background="@drawable/ic_launcher"
                    android:scaleType="centerCrop" />
                <ImageView
                    android:layout_width="match_parent"
                    android:layout_height="200dp"
                    android:background="@drawable/ic_launcher"
                    android:scaleType="centerCrop" />
            </LinearLayout>
            <include android:id="@+id/normal" layout="@layout/stick_layout" />
        </FrameLayout>
    </com.xys.scrolltrick.TrickScroll>
</LinearLayout>

這裡加入多個 ImageView,是為了讓畫面能夠滾動起來。

二、為 ScrollView 加上滾動監聽

由於 ScrollView 本身並沒有提供滾動監聽,因此我們只能自行改寫,建立一個監聽介面:

package com.xys.scrolltrick;

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

public class TrickScroll extends ScrollView {
    public interface onScrollListener {
        public void onScroll(int scrollY);
    }

    private onScrollListener onScrollListener;

    public TrickScroll(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

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

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

    public void setOnScrollListener(onScrollListener onsScrollListener) {
        this.onScrollListener = onsScrollListener;
    }

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

三、主程式

package com.xys.scrolltrick;

import android.app.Activity;
import android.os.Bundle;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.LinearLayout;
import com.xys.scrolltrick.TrickScroll.onScrollListener;

public class MainActivity extends Activity implements onScrollListener {
    private TrickScroll mScroll;
    private LinearLayout mLayout1; // 正常狀態下的版面
    private LinearLayout mLayout2; // 頂部吸附的版面

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mScroll = (TrickScroll) findViewById(R.id.scrollView);
        mLayout1 = (LinearLayout) findViewById(R.id.stick);
        mLayout2 = (LinearLayout) findViewById(R.id.normal);
        mScroll.setOnScrollListener(this);
        // 在根版面狀態下,監聽版面變化
        findViewById(R.id.parent_layout).getViewTreeObserver()
                .addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        onScroll(mScroll.getScrollY());
                    }
                });
    }

    @Override
    public void onScroll(int scrollY) {
        // 取得正常版面的位置來重新設定吸附版面的位置
        int layoutTop = Math.max(scrollY, mLayout1.getTop());
        mLayout2.layout(0, layoutTop, mLayout2.getWidth(), layoutTop + mLayout2.getHeight());
    }
}

四、原理說明

整個效果的核心就在 onScroll(int scrollY) 這個方法中,我們用 max 函式來判斷當前應採用的位置。

這裡要特別注意兩個方法:

  1. getTop():回傳該 view 到其父容器的 top 像素距離。
  2. getScrollY():回傳 ScrollView 已經滚動了多少。

理解這兩個方法後,判斷邏輯就很清楚了:當滾動距離小於 getTop() 時,吸附版面維持與正常版面一致的位置;一旦大於 getTop(),就改用 getScrollY() 來定位,讓它固定在頂端。

如果不好理解,可以把版面想像成一條紙帶,而手機螢幕是一個挖了孔的框,我們從後面由下往上拉紙帶,這樣就模擬了 scroll 的滑動,會比較容易掌握。

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