Search code examples
androidlayoutandroid-framelayoutandroid-layout-weight

FrameLayout with layout_weight is considered useless


Consider the following layout:

<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black"
>
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2"
    />
    <TextView
        android:id="@+id/primary_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="@color/white"
        android:textSize="24sp"
        tools:text="Primary!"
    />
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
    />
    <TextView
        android:id="@+id/secondary_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="@color/white"
        android:textSize="24sp"
        tools:text="Secondary!"
    />
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="3"
    />
</LinearLayout>

See the screenshot below for the result. The layout works fine, but Android Studio warns me that the FrameLayouts are considered useless and should be removed. However, they're not useless. I use layout_weight here. The idea is that the space between and around the two TextViews are relative with weights 2:1:3.

How can I rewrite my layout that results in the same weighted positioning of the views without having to use empty FrameLayouts?

screenshot


Solution

  • FrameLayout is a container that is supposed to have children. For a gap, a View is sufficient. I replaced each empty FrameLayouts with:

    <View
      android:layout_width="match_parent"
      android:layout_height="0dp"
      android:layout_weight="1"
      />
    

    and the linter warning was gone.