Search code examples
androidlayoutandroid-linearlayoutfloating-action-button

Android: Layout for dynamic buttons + FAB + Appbar


I'm new to Android (and Java) and have difficulties with the layouts.

When I click on the FAB, a button should be created. As I learned, I must use LinearLayout when I want to add buttons programmatically. This is generally working, but when I try to combine the LinearLayout with the FAB and the appbar, either the newly created button is not shown or the FAB or the appbar.

One of the layouts hides always some of the other elements. It should look that way:

  1. Appbar

  2. LinearLayout - Buttons with scroll bar

  3. FAB on the bottom right

I tried with RelativeLayout, FrameLayout, CoordinatorLayout etc., no luck.

activity_main.xml

<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"
    tools:context="xyz.mypackage.MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/main_layout">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    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:popupTheme="@style/AppTheme.PopupOverlay" />

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

</LinearLayout>

<!--include layout="@layout/content_main" /-->

<android.support.design.widget.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"
    android:visibility="visible"
    app:srcCompat="@android:drawable/ic_input_add" />

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

Solution

  • After reading the documentation (yes, I should have done that before posting a question), I found out a way to do it:

    As root, use a RelativeLayout, then for the appbar and buttons use a LinearLayout as child (I also added a ScrollView with another LinearLayout). The FAB should be within the root (RelativeLayout) with the following attributes:

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