如何使Android支持屏幕右下角的悬浮按钮?

4

我在RelativeLayout布局中添加了一个FloatingActionButton,如下所示

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|right"
        android:layout_margin="16dp"
        android:clickable="true"
        android:src="@drawable/ic_ok" />

</RelativeLayout>

如您所见,我已将 layout_gravity 设置为 bottom|right,但是我的 FloatingActionButton 的位置没有改变,它仍然停留在左上角。

我该如何让我的 FloatingActionButton 在右下角?

4个回答

10

使用 CoordinatorLayout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<RelativeLayout
    android:id="@+id/test"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</RelativeLayout>

<android.support.design.widget.FloatingActionButton
    android:layout_margin="10dp"
    android:id="@+id/myFAB"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:backgroundTint="#FF0000"
    app:borderWidth="0dp"
    app:elevation="8dp"
    app:layout_anchor="@id/test"
    app:layout_anchorGravity="bottom|right|end" />
</android.support.design.widget.CoordinatorLayout>

注意

   app:layout_anchor="@id/test"
   app:layout_anchorGravity="bottom|right|end"

协调者布局旨在处理这些情况。如果我是你,我会坚持使用它 @DäñishShärmà - Blackbelt
我已经根据你的答案编辑了我的代码,并点赞了你的回答。还有一件事,我想问如何更改浮动按钮的背景颜色。我想让它与我的colorPrimaryDark颜色相同。这可能吗? - Däñish Shärmà
如果您有app:backgroundTint="#FF0000",请将其删除。默认情况下,如果您的主题设置正确,您应该会得到它。 - Blackbelt

7
由于您将FloatingActionButton包装在RelativeLayout中,请使用以下属性:

相对布局属性:

android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"

希望这有所帮助。

0

清除您的代码中的:

android:layout_gravity="bottom|right"

添加以下行:

app:layout_anchorGravity="bottom|right|end"


0

清除您的代码中的:
android:layout_gravity="bottom|right"

添加以下内容:
app:layout_anchorGravity="bottom|right|end"


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