You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何借助Material库将FloatingActionButton设置为方形?

把Material库的FloatingActionButton设置为方形的方法

嘿,要把FloatingActionButton(简称FAB)改成方形其实超简单,Material Components库已经给我们提供了直接的配置方式,不用折腾自定义View。结合你给出的现有代码,我给你两种可行的方案:

方案一:直接在布局中设置圆角为0

这是最快捷的方式,直接给FAB添加app:cornerRadius属性并设为0dp,就能让圆角消失变成方形:

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:fabSize="mini"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_margin="16dp"
    app:cornerRadius="0dp" /> <!-- 核心属性:将圆角设为0实现方形 -->

方案二:用ShapeAppearance样式统一管理(适合多FAB场景)

如果你的项目里有多个FAB都需要方形样式,推荐用统一的Shape样式来管理,方便后续修改:

首先在res/values/styles.xml中定义一个方形的Shape样式:

<style name="SquareFabShape" parent="ShapeAppearance.MaterialComponents.SmallComponent">
    <item name="cornerSize">0dp</item>
</style>

然后在FAB的布局中引用这个样式:

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:fabSize="mini"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_margin="16dp"
    app:shapeAppearance="@style/SquareFabShape" />

额外提示

  • 确保你的App主题是继承自Theme.MaterialComponents.*(就像你代码里的Theme.MaterialComponents.Light.NoActionBar),这样Material库的专属属性才能正常生效。
  • 如果需要自定义FAB的大小,除了用app:fabSize,也可以直接设置固定的android:layout_width和android:layout_height(比如56dp),配合圆角属性就能得到你想要的方形尺寸。

内容的提问来源于stack exchange,提问作者WHOATEMYNOODLES

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 19:54:06