Search code examples
androidandroid-viewpagerandroid-tablayoutandroid-coordinatorlayoutfloating-action-button

FloatingActionButton appearing under screen when using TabLayout and ViewPager


Take a look at the FAB below:

Image

It's not appearing unless I collapse the Toolbar. Here's my XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/toolbar"
    android:layout_marginTop="0dp"
    android:animateLayoutChanges="true"
    android:background="@android:color/white"
    android:layoutDirection="locale"
    android:orientation="vertical"
    android:padding="0dp">

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/cLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="0dp" />

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:background="@color/accent"
            android:src="@drawable/ic_add"
            app:layout_anchor="@id/list"
            app:layout_anchorGravity="bottom|end" />
    </android.support.design.widget.CoordinatorLayout>
</RelativeLayout>

Why is this happening if I set no behavior for the FAB? Is there any property I should add to anything so I could prevent this behaviour?


Solution

  • Simply remove your FloatingActionButton from each Fragment and add it to your Activity. This way not only the FAB stays in place but it also fixes your problem. Then you can use getActivity().findViewByIf(id) in your Fragment and set an onClickListener in each Fragment.