Skip to content
Advertisement

Problem with positioning FloatingActionButton in Fragment

I have problem with positioning FAB inside Fragment. FAB is on the top left, but I need it on the bottom right.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.vrhcaby.VrhcabyFragment">

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textAlignment="center"
    android:src="@mipmap/dice_180"
    android:layout_margin="100px" />

<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"
    app:srcCompat="@android:drawable/ic_dialog_email" />

 </RelativeLayout>

enter image description here

What I have wrong?

Advertisement

Answer

as I have read , FAB doesn’t work with relative layout very well and you should use Coordinator Layout instead.

  • first include its dependency in build.gradle(Module:app)
dependencies {
    ...
    implementation 'androidx.coordinatorlayout:coordinatorlayout:1.1.0'
    ...
}
  • then declare Coordinator Layout like this instead of relative layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.vrhcaby.VrhcabyFragment">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textAlignment="center"
        android:src="@mipmap/dice_180"
        android:layout_margin="100px" />

    <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"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

If you want more information you can read more about the FAB here

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement