FloatingActionButton with BottomNavigationView

Xmstr picture Xmstr · Mar 30, 2017 · Viewed 7.6k times · Source

I cant position my FAB. It should be bottom right, but on top of the BottonNavigationView.

1) Can i achieve this without RelativeLayout inside coordinateLayout?

2) Show me how

3) Should i use FrameLayout as a container for fragments?

<android.support.design.widget.CoordinatorLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay">

    </android.support.v7.widget.Toolbar>

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

<FrameLayout
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

</FrameLayout>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab_electricity"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="@dimen/fab_margin"
    app:layout_anchorGravity="bottom|right|end"
    app:srcCompat="@drawable/ic_add_electro" />

<android.support.design.widget.BottomNavigationView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_gravity="bottom">

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

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

result

Answer

LightYearsBehind picture LightYearsBehind · Mar 31, 2017

A quick search to FloatingActionButton.Behavior tells us the following thing.

@Override
public void onAttachedToLayoutParams(@NonNull CoordinatorLayout.LayoutParams lp) {
    if (lp.dodgeInsetEdges == Gravity.NO_GRAVITY) {
        // If the developer hasn't set dodgeInsetEdges, lets set it to BOTTOM so that
        // we dodge any Snackbars
        lp.dodgeInsetEdges = Gravity.BOTTOM;
    }
}

Since BottomNavigationView also resides at the bottom of the layout. Add following element to your BottomNavigationView and CoordinatorLayout will handle the inset and dodging for you automatically.

app:layout_insetEdge="bottom"