如何在包含RecyclerView的Fragment中将FAB对齐到屏幕右下角
问题根源
你遇到的问题核心是两层布局限制导致FAB无法对齐屏幕右下角:
NestedScrollView默认不会让内部子控件撑满自身可视区域,即便子控件设置match_parent也不会生效,导致Fragment的根布局高度最多只能等于内容总高度,无法铺满屏幕- 你当前将FAB放在
NestedScrollView内部的Fragment中,默认会跟随滚动列表一起滑动,无法固定在屏幕固定位置
解决方案
方案一(推荐,符合Material Design规范)
直接将FAB移到activity_main.xml的CoordinatorLayout下作为直接子控件,天然支持固定位置和滚动联动效果:
<!-- activity_main.xml 新增FAB到CoordinatorLayout节点末尾 --> <com.google.android.material.floatingactionbutton.FloatingActionButton android:id="@+id/id_floating_button_e_shops" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_margin="16dp" android:contentDescription="@string/add_a_shop" android:src="@drawable/ic_plus" app:tint="@color/white" app:maxImageSize="30dp" app:useCompatPadding="true"/>
如果只需要在activity_user_shops_list Fragment显示时展示FAB,只需在Activity中封装FAB可见性控制方法,在对应Fragment的onResume中设置为View.VISIBLE,onPause中设置为View.GONE即可。
方案二(保留FAB在Fragment布局内)
需要依次修改以下3处布局属性:
- 修改
activity_main.xml中的NestedScrollView属性:
<androidx.core.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="match_parent" <!-- 改wrap_content为match_parent --> android:fillViewport="true" <!-- 新增这一行,允许子view撑满ScrollView可视区域 --> app:layout_behavior="@string/appbar_scrolling_view_behavior"> <androidx.fragment.app.FragmentContainerView android:id="@+id/id_fragment_container_m" android:layout_width="match_parent" <!-- 改wrap_content为match_parent --> android:layout_height="match_parent" <!-- 改wrap_content为match_parent --> /> </androidx.core.widget.NestedScrollView>
- 修改
fragment_user_shops_list.xml的根布局属性:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" <!-- 改wrap_content为match_parent --> android:layout_height="match_parent" <!-- 改wrap_content为match_parent --> android:background="@color/null_gray">
- 给FAB添加对齐属性:
<com.google.android.material.floatingactionbutton.FloatingActionButton android:id="@+id/id_floating_button_e_shops" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_alignParentBottom="true" android:layout_margin="16dp" <!-- 其余原有属性保持不变 --> />
内容的提问来源于stack exchange,提问作者Intelligence
相关产品推荐
相关产品推荐

