Android 中的浮动操作按钮图标不在中心

Floating Action Button in Android having icon not in center

这是XML:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout 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=".MainActivity">

<TextView
    android:id="@+id/test"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:text="Hello World!" />

<android.support.design.widget.FloatingActionButton
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:layout_marginBottom="4dp"
    android:scaleType="center"
    android:src="@drawable/button_floating_add"
    app:borderWidth="0dp"
    app:elevation="8dp" />

</RelativeLayout>

输出如下所示:

我认为这是由于 API 版本发生了变化。我使用 compileSDK 和 targetSDK 版本 28 以及设计和 appcompat 库作为 28.0.0。当我将 API 和设计库版本更改回 26 时,输出如下所示:

您是否尝试过使用 Android Asset Studio?他们几乎可以导入各种尺寸和密度的所有基本绘图。这是 link https://developer.android.com/studio/write/image-asset-studio.html

根据视图的高度和宽度使用此 属性

app:fabCustomSize="40dp"

并建议 you.svg 文件而不是 .png。

你能试试这些属性吗,

android:layout_gravity="bottom|center"
android:layout_centerHorizontal="true"
android:scaleType="fitCenter"

floating action button anatomy

FAB containers come in two sizes:

  1. Default (56 x 56dp)
  2. Mini (40 x 40dp)

所以在你的情况下你想使用一个小的 FAB。但是您不使用 layout_widthlayout_height 来定义它,因为这只会弄乱填充。您必须使用 app:fabSize 属性并将其设置为 SIZE_MINI:

<android.support.design.widget.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:fabSize="mini"
    ... />

晶圆厂是一种特殊类型的视图,您必须遵守其要求。也就是说它的宽度和高度应该是"wrap_content"。如果您希望您的工厂成为迷你版,您可以添加 app:fabSize="mini"。 您可以使用 layout_gravity 来设置它的屏幕位置(在我下面的示例中,它位于右下角)。此外,图标必须为 24dp x 24dp。我建议从 https://material.io/tools/icons/?style=baseline 下载您的图标,您可以在其中选择图像大小等等。

<com.google.android.material.floatingactionbutton.FloatingActionButton
  android:id="@+id/fab"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_gravity="bottom|end"
  android:layout_margin="@dimen/fab_margin"
  android:onClick="@{() -> viewModel.onFabPressed()}"
  app:srcCompat="@drawable/ic_baseline_add_24px"/> 

上面的 xml 是我的一个应用程序的工作示例。 我希望这对您有所帮助,祝您有美好的一天!