CoordinatorLayout和FloatingActionButton的问题

问题描述

picture 1上看起来不错,但是在picture 2上,因为FAB具有app:layout_anchor="@id/recyclerview_list"属性,所以看起来不太好。有没有一种方法可以在不添加自定义底部导航栏的情况下将FAB锚定到底部?我只是希望该按钮永久保持在原位,即使RecyclerView更改其高度也是如此。

这是XML文件

<androidx.coordinatorlayout.widget.CoordinatorLayout
android:id="@+id/main_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="fragments.DailyListFragment">

<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/appbar_layout"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <com.google.android.material.appbar.CollapsingToolbarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_scrollFlags="scroll|snap|exitUntilCollapsed"
        app:title="@string/sample"
        app:contentScrim="@color/accent_color1">

        <ProgressBar
            android:id="@+id/progressBar2"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:progresstint="#BA0E0E" />

        <androidx.appcompat.widget.Toolbar
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Dark"/>

    </com.google.android.material.appbar.CollapsingToolbarLayout>

</com.google.android.material.appbar.AppBarLayout>

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/fab_new_item"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="24dp"
    android:layout_marginBottom="24dp"
    android:src="@drawable/ic_add_black_24dp"
    android:visibility="visible"
    app:fabSize="normal"
    app:layout_anchor="@id/recyclerview_list"
    app:layout_anchorGravity="bottom|right|end"/>

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerview_list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:alwaysDrawnWithCache="false"
    android:background="@color/colorBackground"
    android:visibility="visible"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:listitem="@layout/recyclerview_layout_list">

</androidx.recyclerview.widget.RecyclerView>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

解决方法

替换

<com.google.android.material.floatingactionbutton.FloatingActionButton
    app:layout_anchor="@id/recyclerview_list" 
    app:layout_anchorGravity="bottom|right|end"

使用

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:layout_gravity="bottom|end"