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

Android 滑動到頂部懸停效果的兩種實現思路

編輯:關於 Android 程式設計

先看目標效果:

思路一:多寫一份布局做「替身」

網上大量教程用的是這種土辦法:在需要懸浮的區域之外,再寫一個一模一樣的 layout,初始可見性設為 gone。當內容滑動到那個位置時,把替身布局設為 VISIBLE,視覺上就變成「懸停在頂部不動」。

這個方案缺點明顯:布局重復、狀態需要手動同步,一旦懸浮區域結構複雜就很難維護。

思路二:用 design 包的 CoordinatorLayout

更省事的做法是借助 Design Support Library,讓系統幫你處理懸停邏輯:

 <android.support.design.widget.CoordinatorLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:app="https://schemas.android.com/apk/res-auto" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context="com.peipei.app.MainActivity"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="250dp"> <android.support.design.widget.CollapsingToolbarLayout app:layout_scrollFlags="scroll" app:contentScrim="#000000" android:layout_width="match_parent" android:layout_height="220dp"> <TextView android:text="banner區域" android:gravity="center" android:textColor="#ffffff" android:background="#987545" android:layout_width="match_parent" android:layout_height="220dp"/> </android.support.design.widget.CollapsingToolbarLayout> <TextView android:gravity="center" android:layout_width="match_parent" android:layout_height="30dp" android:text="懸浮的部分"/> </android.support.design.widget.AppBarLayout> <android.support.v4.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="@dimen/text_margin" android:text="@string/large_text"/> </android.support.v4.widget.NestedScrollView> </android.support.design.widget.CoordinatorLayout>

三步搞定

  1. 把需要懸浮的 layout 放在 CollapsingToolbarLayout 之外、AppBarLayout 之內——這是它不會被捲走的原因。
  2. 給 CollapsingToolbarLayout 設置 app:layout_scrollFlags="scroll",聲明它參與滾動。
  3. 給滾動容器(NestedScrollView / RecyclerView 等)設置 app:layout_behavior="@string/appbar_scrolling_view_behavior"。

記得根布局必須是 CoordinatorLayout,否則整套約定不生效。

最終效果:

對比之下,第二種方案不用維護重復布局,也不用手動記錄滑動距離,代碼量更少也更可靠,推薦優先使用。

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