Search code examples
androidkotlinfloating-action-button

Android : How to set gravity of Floating Action Button Programmatically?


I want to move the position of Floating action button programmatically at a certain place in some fragment because sometimes the floating action is covering the important contents of that fragment. I got the reference of floating action button in the activity and stored it in a static variable.I am trying to change its gravity in the onResume method of the fragment. As you can see in the image that fab is covering y-axis so I want to move it to the END. Image for the reference.

The code in the onResume method of the fragment(not working):

override fun onResume() {
    super.onResume()
    val params : CoordinatorLayout.LayoutParams = BaseActivity.fab!!.layoutParams as CoordinatorLayout.LayoutParams
    params.anchorGravity = GravityCompat.END
    BaseActivity.fab!!.layoutParams = params
}

XML file of main activity

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.mandar.hackerthon_app.Activities.BaseActivity"
    tools:showIn="@layout/app_bar_base">

    <FrameLayout
        android:id="@+id/frameBaseFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></FrameLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:layout_margin="20dp"
        android:scaleType="center"
        android:elevation="10dp"
        app:backgroundTint="@color/common_google_signin_btn_text_dark_default"
        app:srcCompat="@mipmap/ic_connection_on_round" />

</android.support.design.widget.CoordinatorLayout>

Solution

  • In your XML file, add the app:layout_anchor property for FloatingActionButton, as layout_anchorGravity is only taken into account if you specify an anchor view.

    In your case, this anchor may be @id/frameBaseFragment. Note that if you want to move FloatingActionButton to the bottom-end of its CoordinatorLayout parent, you may instead change the value of layoutGravity.

    Also, it is strongly discouraged to store references to Views in static variables as it prevents the associated Activity from being garbage-collected, causing huge memory leaks. This might also be the cause of your problem.