Android快速实现头部悬浮效果

Updated on with 662 views

使用Google默认提供的design包中的控件CoordinatorLayout和AppBarLayout即可快速实现。布局代码如下:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

    </data>

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#F6F7F8">

        <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#F6F7F8"
            app:elevation="0dp">

         <TextView
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:background="#46ED84"
            android:gravity="center"
            android:text="头部滚动部分"
            app:layout_scrollFlags="scroll"/>
 
        <TextView
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:background="#FFDB87"
            android:gravity="center"
            android:text="悬停部分"/>
        </com.google.android.material.appbar.AppBarLayout>


        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rvAllFiles"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="@dimen/dp_12"
            android:layout_marginEnd="@dimen/dp_12"
            android:layout_marginBottom="@dimen/dp_26"
            android:background="@drawable/shape_bg_white_5_bottom"
            android:overScrollMode="never"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    </androidx.coordinatorlayout.widget.CoordinatorLayout>
</layout>

需要注意的是:

  1. 使用CoordinatorLayout包裹AppBarLayout
  2. 将上部分需要滚动隐藏和悬浮的部分放在AppBarLayout中
  3. 将需要滚动隐藏的View里面加上app:layout_scrollFlags="scroll"
  4. 设置AppBarLayout的elevation为0dp,取消View的深度(高度)
  5. AppBarLayout平级中放可滑动的view
  6. 可滚动的View加上app:layout_behavior="@string/appbar_scrolling_view_behavior"


标题:Android快速实现头部悬浮效果
作者:yanjing
地址:https://yanjingtp.cn/articles/2022/03/11/1646967938601.html