如何更改 android 上的浮动操作按钮 (FAB) 的形状?

How to change the shape of Floating Action Button (FAB) on android?

在我们的 android 应用中,我们需要创建一个浮动操作按钮,它不是默认的圆形,而是一个具有三个圆角的正方形。晶圆厂如下图所示:

我设法创建了这样一个表格,但不知道如何将它应用到我的晶圆厂,甚至不知道如何应用它。形状的 xml 文件如下所示:

   <shape xmlns:android="http://schemas.android.com/apk/res/android"
      android:shape="rectangle">
    <solid android:color="@color/red" />
    <corners
      android:topLeftRadius="90dp"
      android:topRightRadius="90dp"
      android:bottomRightRadius="90dp"/>
   </shape>

我尝试用

更改表格
android:src="@drawable/my_shape"

但这只会改变我按钮内的图标。 我想我需要扩展 FloatingActionButton,但我不知道该怎么做。

有没有办法改变晶圆厂的形状?如果有人已经实现了这一点,我将不胜感激。

您正在寻找的是更改按钮的背景

android:background="@drawable/my_shape"

支持库提供的FloatingActionButton无法扩展,因为需要替换的方法被设置为私有。 Material Components (which is the official AndroidX replacement for the support library) has Shape Theming on the roadmap ~10 月至 12 月,这将让您正式且轻松地做到这一点(无需扩展视图)。

但是暂时还没有,所以我分叉了customFloatingActionButton by robertlevonyan, and with some slight modifications, it allows you to use your own custom shape. The source code is available here

要使用 Gradle 将其添加到您的项目中,您需要使用 jitpack。您可以这样添加:

allprojects {
   repositories {
       ...
       maven { url 'https://jitpack.io' }
   }
}

然后实现我的fork:

implementation 'com.github.JediBurrell:customFloatingActionButton:-SNAPSHOT'

接下来我们将创建形状,您创建的那个应该可以正常工作。

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <corners
        android:topLeftRadius="@dimen/fab_circle_radius"
        android:topRightRadius="@dimen/fab_circle_radius"
        android:bottomRightRadius="@dimen/fab_circle_radius" />
    <solid android:color="@color/colorAccent" />
</shape>

然后最后将其添加到您的布局中(Github 存储库中列出了更多 FAB 选项):

<com.jediburrell.customfab.FloatingActionButton
    android:id="@+id/floating_action_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|right"
    android:layout_margin="16dp"
    app:fabType="custom"
    app:fabShape="@drawable/fab_teardrop"
    app:fabIcon="@drawable/ic_add_24dp"
    app:fabColor="@color/red" />

这是它的样子:

借助 Material 组件库,您可以使用 shapeAppearanceOverlay:

<com.google.android.material.floatingactionbutton.FloatingActionButton
    app:shapeAppearanceOverlay="@style/fab_3_rounded"
    .../>

与:

<style name="fab_3_rounded">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">50%</item>
    <item name="cornerSizeBottomLeft">0dp</item>
</style>

无需更新任何外部库从

更新您的 Gradle 文件
implementation 'com.google.android.material:material:1.1.0'

implementation 'com.google.android.material:material:1.3.0'

这将使您能够访问

  <com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

然后您可以像普通按钮一样更改其属性