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

模仿知乎回答詳情頁動畫:屬性動畫實現標題欄自動隱藏與工具欄浮現

編輯:關於 Android 程式設計

本篇示範如何還原「知乎」回答詳情頁的滾動動畫:內容向上滑時頂部的標題欄與問題標題往上收起,底部的工具列同時浮現;反向滑動時則全部復位。這個效果不需要任何第三方庫,只用屬性動畫加上自定義 ScrollView 就能完成。

原版效果

先拆需求

動手之前把行為拆清楚(gif 幀數有限看起來不連貫,建議直接裝一個知乎對照著玩):

  • 內容往上移動到一定位置後,最上方的標題欄 Bar 與問題標題 Title 會隱藏,但回答者 Author 區塊不隱藏。
  • 內容往下移動到一定位置後,原本隱藏的 Bar 與 Title 會重新下降顯示。
  • 內容往上滑時,底部隱藏的 Tools 會上升顯示。
  • 內容往下滑時,若 Tools 正在顯示則隱藏。
  • Bar 與 Title 下降顯示時,Title 是從 Bar 的「下面」鑽出來的,帶有遮擋層次感。
  • 快速滑動到底部時,隱藏的 Tools 會顯示出來。
  • 快速滑動到頂部時,隱藏的 Bar 與 Title 也會顯示出來。

不拆不知道,一個看似簡單的效果背後有七條規則。

觀察原版結構

用 ADT 附帶的 View Hierarchy 工具看一下知乎是怎麼搭的:

右側的分析圖透露了幾個資訊:內容區用的是 WebView(使用者回答的格式太複雜,WebView 是最合理的選擇);標題欄是一個 View;最下方則是一個 LinearLayout 包了四顆 ToggleButton。

我們沒有 WebView,就用 ScrollView 代替;上面的頭部也簡化成一張 ImageView 加個 src。版面簡化後,邏輯不變。

一、底部 Tools 的顯示與隱藏

屬性動畫與 frame 動畫都能做到位移,但屬性動畫會真正改變 View 的 y 值,後續的點擊事件位置才會跟著對上,因此這裡選用屬性動畫。

 /** 顯示工具欄 */
private void showTools() {
    ObjectAnimator anim = ObjectAnimator.ofFloat(img_tools, "y",
            img_tools.getY(), img_tools.getY() - img_tools.getHeight());
    anim.setDuration(TIME_ANIMATION);
    anim.start();
    isToolsHide = false;
}

/** 隱藏工具欄 */
private void hideTools() {
    ObjectAnimator anim = ObjectAnimator.ofFloat(img_tools, "y",
            img_tools.getY(), img_tools.getY() + img_tools.getHeight());
    anim.setDuration(TIME_ANIMATION);
    anim.start();
    isToolsHide = true;
} 

至於呼叫時機:手指往上滑時顯示、往下滑時隱藏。因此監聽 ScrollView 的 onTouch,判斷手指方向即可。

 mScroller.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            lastY = event.getY();
            break;
        case MotionEvent.ACTION_MOVE:
            float disY = event.getY() - lastY;
            // 超過 touchSlop 才算一次有效滑動,過濾掉手指的細微抖動
            if (Math.abs(disY) > viewSlop) {
                isUpSlide = disY < 0;
                if (isUpSlide) {
                    if (!isToolsHide) hideTools();
                } else {
                    if (isToolsHide) showTools();
                }
            }
            break;
        }
        return false;   // 不攔截事件,讓 ScrollView 正常滾動
    }
}); 

用 isToolsHide 這個旗標避免動畫被重複觸發。這裡 return false 是刻意的——一旦回傳 true,ScrollView 的內建滾動就會失效。

二、頂部布局的動畫

思路與底部相同,也是屬性動畫改 y 值,只是這次涉及三個 View:Bar、Title 與包裹它們的根布局 fl_top。

為什麼 Author 區塊不單獨移動?因為 fl_top 一動,它的子 View 會跟著動,所以只移動根布局就夠了。知乎的做法是讓 WebView(我們這裡是 ScrollView)佔滿整個畫面,其他布局都疊在 FrameLayout 裡,這樣文字能獲得最大顯示空間;代價是首次載入時頂部內容會被遮住,需要預留一段空白。

三、版面配置

 <FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white" >

    <com.socks.zhihudetail.MyScrollView
        android:id="@+id/scroller"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:textSize="16sp"
            android:textColor="@android:color/black"
            android:text="@string/hello_world"/>
    </com.socks.zhihudetail.MyScrollView>

    <FrameLayout
        android:id="@+id/ll_top"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/white"
        android:layout_gravity="top">
        <ImageView
            android:id="@+id/img_author"
            android:layout_width="match_parent"
            android:layout_height="80dp"
            android:scaleType="fitXY"
            android:src="@drawable/bg_author"/>
        <TextView
            android:id="@+id/tv_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="55dp"
            android:text="為什麼美國有那麼多肌肉極其強大的肌肉男?"
            android:textSize="18sp"
            android:background="#DBDBDB"
            android:gravity="center|left"
            android:paddingLeft="15dp"
            android:paddingRight="15dp"
            android:paddingTop="5dp"
            android:paddingBottom="5dp"
            android:textColor="@android:color/darker_gray" />
        <ImageView
            android:id="@+id/img_bar"
            android:layout_width="match_parent"
            android:layout_height="55dp"
            android:scaleType="fitXY"
            android:src="@drawable/bg_actionbar"/>
    </FrameLayout>

    <ImageView
        android:id="@+id/img_tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="fitXY"
        android:layout_gravity="bottom"
        android:src="@drawable/bg_bottom"/>
</FrameLayout> 

四、為什麼用 FrameLayout 而不是 LinearLayout

這裡有段踩坑經驗值得記錄。最初用 LinearLayout 時,Title 往下移動顯示會蓋在 Bar 上面——原因很直白,LinearLayout 的子 View 沒有層次概念,後宣告的會蓋住前面的。嘗試用 View.bringToFront() 把 Bar 提前,結果版面反而亂了:bringToFront 會觸發重新測量與配置,Bar 不再遵守 LinearLayout 的排列規則,首次載入時直接跑到最下面。

改用 FrameLayout 雖然解決了層次問題(FrameLayout 中後加入的子 View 自然疊在上層,把 img_bar 放在最後即可),但換來另一個麻煩:Bar 的高度是固定的 55dp,Title 的高度卻會隨文字行數變化,導致 Author 區塊無法用固定 marginTop 定位。解法是在程式碼中動態計算兩者高度之和,再設定 marginTop。

五、在繪製前取得真實高度

onCreate 階段 View 尚未完成測量,getHeight() 一律回傳 0。用 ViewTreeObserver 的 OnPreDrawListener 攔住「即將繪製」的時機即可拿到真實數值:

 // 取得 Bar 與 Title 的高度,據以設定 author 布局的 marginTop
ViewTreeObserver viewTreeObserver = fl_top.getViewTreeObserver();
viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
    @Override
    public boolean onPreDraw() {
        if (!hasMeasured) {
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.MATCH_PARENT,
                    FrameLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(0, img_bar.getHeight() + tv_title.getHeight(), 0, 0);
            img_author.setLayoutParams(layoutParams);
            hasMeasured = true;   // 只執行一次,否則會造成無限重繪
        }
        return true;
    }
}); 

hasMeasured 這個旗標不可省略——在 onPreDraw 中修改布局會觸發新一輪繪製,若每次都改就會陷入無限迴圈。

六、自定義 ScrollView 監聽滾動距離

知乎的這個界面是依據一個固定閾值來切換顯示狀態的,所以我們需要知道滾動距離。原生 ScrollView 沒有提供這樣的監聽器,只能自己重寫 onScrollChanged:

 public class MyScrollView extends ScrollView {

    private BottomListener bottomListener;
    private onScrollListener scrollListener;

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

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

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);

        if (getScrollY() + getHeight() >= computeVerticalScrollRange()) {
            if (null != bottomListener) {
                bottomListener.onBottom();     // 已滑到底
            }
        }
        if (null != scrollListener) {
            scrollListener.onScrollChanged(l, t, oldl, oldt);  // 實時位置
        }
    }

    public void setBottomListener(BottomListener bottomListener) {
        this.bottomListener = bottomListener;
    }

    public void setScrollListener(onScrollListener scrollListener) {
        this.scrollListener = scrollListener;
    }

    public interface onScrollListener {
        public void onScrollChanged(int l, int t, int oldl, int oldt);
    }

    public interface BottomListener {
        public void onBottom();
    }
} 

註冊監聽器:

 mScroller.setBottomListener(this);
mScroller.setScrollListener(this); 

七、串起所有動畫

 /** 顯示上部布局 */
private void showTop() {
    ObjectAnimator anim1 = ObjectAnimator.ofFloat(img_bar, "y", img_bar.getY(), 0);
    anim1.setDuration(TIME_ANIMATION);
    anim1.start();

    ObjectAnimator anim2 = ObjectAnimator.ofFloat(tv_title, "y",
            tv_title.getY(), img_bar.getHeight());
    anim2.setInterpolator(new DecelerateInterpolator());  // 減速,模擬從 Bar 下方滑出
    anim2.setDuration(TIME_ANIMATION + 200);
    anim2.start();

    ObjectAnimator anim4 = ObjectAnimator.ofFloat(fl_top, "y", fl_top.getY(), 0);
    anim4.setDuration(TIME_ANIMATION);
    anim4.start();

    isTopHide = false;
}

/** 隱藏上部布局 */
private void hideTop() {
    ObjectAnimator anim1 = ObjectAnimator.ofFloat(img_bar, "y", 0, -img_bar.getHeight());
    anim1.setDuration(TIME_ANIMATION);
    anim1.start();

    ObjectAnimator anim2 = ObjectAnimator.ofFloat(tv_title, "y",
            tv_title.getY(), -tv_title.getHeight());
    anim2.setDuration(TIME_ANIMATION);
    anim2.start();

    ObjectAnimator anim4 = ObjectAnimator.ofFloat(fl_top, "y", 0,
            -(img_bar.getHeight() + tv_title.getHeight()));
    anim4.setDuration(TIME_ANIMATION);
    anim4.start();

    isTopHide = true;
}

/** 滑到底部時,確保工具欄是顯示的 */
@Override
public void onBottom() {
    if (isToolsHide) {
        showTools();
    }
}

/** 依滾動距離切換頂部顯示狀態 */
@Override
public void onScrollChanged(int l, int t, int oldl, int oldt) {
    if (t <= dp2px(TOP_DISTANCE_Y) && isTopHide && isAnimationFinish) {
        showTop();
    } else if (t > dp2px(TOP_DISTANCE_Y) && !isTopHide && isAnimationFinish) {
        hideTop();
    }
} 

兩個實作上的提醒

isAnimationFinish 為什麼必要?快速滑動時 onScrollChanged 會以極高頻率觸發,若不加上「動畫是否正在進行」的判斷,同一個動畫會被連續啟動十幾次,畫面會出現明顯的抖動與延遲。實務做法是啟動動畫時把旗標設為 false,在 AnimatorListener 的 onAnimationEnd 中設回 true。

dp2px 換算不可省略。滾動距離 t 的單位是像素,而 TOP_DISTANCE_Y 寫在程式碼裡通常是以 dp 思考的,直接比較會在不同密度的螢幕上得到完全不同的行為。

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