浮动操作按钮图标未居中显示

11

我正在尝试使用FAB,但是按钮内部的图标被放置在按钮的右下方:

带图标的 FAB 并未居中

这是xml中的FAB定义:

<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/centerLocationButton"
            style="@style/Widget.MaterialComponents.FloatingActionButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_margin="@dimen/pro_arriving_map_location_button_padding"
            android:src="@drawable/ic_my_location"
            app:backgroundTint="@color/white"
            app:fabSize="mini" />

    </RelativeLayout>

我做错了什么?


显示 @drawable/ic_my_location - serg3z
关于在FAB src中使用您的图像,以下答案可能有所帮助: Fab icon not centered - Ali Khaki
1
可能是Android:浮动按钮图标未居中的重复问题。 - Ali Khaki
可能是重复的问题:https://stackoverflow.com/a/59455009/3974530 - InsaneCat
8个回答

8
这似乎是Design Support Library v28.0.0中的一个错误。

我可以通过在代码中编程设置scaleType来解决这个问题。

在您的情况下,在Java/Kotlin代码中:

centerLocationButton.setScaleType(ImageView.ScaleType.CENTER)

1
是的,最终我也做了同样的事情。 - Gastón Sanguinetti

8

My solution is app:fabCustomSize="56dp"


3
如果您正在使用材料设计并使用自定义大小:
android:layout_width="80dp"
android:layout_height="80dp"

替代

android:layout_width="wrap_content"
android:layout_height="wrap_content"

解决方法是使用这两个属性。
app:fabCustomSize="80dp"
app:maxImageSize="70dp"

确保这一点

app:fabCustomSize = the same size as your layout_width
app:maxImageSize= about 10dp minus the size of your layout_width

1
在我的情况下,这个解决方案运行良好 app:fab_icon="@drawable/btn_back_to_top_3x" 查看图片 而不是 android:src="@drawable/btn_back_to_top_3x 查看图片 您还可以添加 android:scaleY="1.X" android:scaleX="1.X" 以获得额外的变化。

0

在更新到SDK 28之后,我遇到了同样的问题。改变大小、scaleType、layout_gravity等都会返回相同的结果。

我目前的短期解决方案是使用ImageButton。


0

尝试使用app:srcCompat而不是android:src。如果您只使用了FAB(根据您发布的图片判断),那么您可能不需要RelativeLayout作为父级,可以使用android:layout_gravity="bottom|end"


0

尝试一下

android:width="wrap_content"
android:height="wrap_content"
app:maxImageSize ="56dp"

在设备上运行。对我来说有效。


0
请尝试给出的解决方案。它对我有效。
<com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="75dp"
        android:layout_height="75dp"
        android:layout_gravity="end|bottom"
        android:layout_margin="10dp"
        android:backgroundTint="@color/white"
        android:contentDescription="Chat"
        app:fabCustomSize="75dp"
        android:src="@drawable/chat"
        app:borderWidth="1dp"
        app:useCompatPadding="true" />

哪里是解决方案? - AlexS

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接