如何在android上更改Floating Action Button(FAB)的形状?

问题描述 投票:19回答:3

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

enter image description here

我设法创建了这样一个表格,但不知道如何将它应用到我的工厂,或者甚至可能。该形状的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 android-layout shape floating-action-button
3个回答
14
投票

由于需要替换的方法设置为private,因此无法扩展支持库提供的FloatingActionButton。 Material Components(这是支持库的官方AndroidX替代品)在Shape Theming上有〜10月到12月的roadmap,这将让你正式和轻松地做到这一点(无需扩展视图)。

但是现在还没有,所以在此期间,我将robertlevonyan分叉了customFloatingActionButton,稍作修改,它允许你使用自己的自定义形状。源代码可用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>

然后最后将它添加到您的布局(更多FAB选项列在Github仓库中):

<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" />

这是看起来如何:


0
投票

在你的问题中,你说你试过调整android:src,这显然是错误的方法,因为那个是关于FloatingActionButton的内容。

android:background参数将改变你的形状。请注意it is supposed to be round

我认为这个问题仅仅是一个duplicate,因为other question只对颜色有所了解。

您需要在XML文件中使用它:

android:background="@drawable/my_shape"

0
投票

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

android:background="@drawable/my_shape"
© www.soinside.com 2019 - 2024. All rights reserved.