どっこと備忘録群

アウトプットしないとインプットできない私が Androidアプリ開発をメインとした備忘録を載せています。

FrameLayoutを扱う

FrameLayoutとは

FrameLayoutは、AndroidのViewグループの一つで、すべての子ビューを重ねて配置するという特性を持っている。 かつては重要な用途がありましたが、現在はあまり頻繁に利用されていない。

利用時のポイント

FrameLayoutを理解する上で重要なポイントは以下の2つ。

  1. layout_gravity
  2. 使いどころ

layout_gravity

layout_gravityは、子ビューを親ビューのどこに配置するかを指定する属性。 LinearLayoutにも同様の属性がありますが、FrameLayoutではこれだけで子ビューの配置を決定できる点が異なる。

設定できる値は以下の通りです。|(パイプ)で複数組み合わせることもできる。

  • top: 親ビューの上端に配置
  • bottom: 親ビューの下端に配置
  • start: 親ビューの左端に配置
  • end: 親ビューの右端に配置
  • center_vertical: 親ビューの垂直方向の中央に配置
  • center_horizontal: 親ビューの水平方向の中央に配置
  • center: 親ビューの上下左右の中央に配置

実装サンプル

topstartはデフォルト位置のため、それ以外の配置を試すサンプルコードです。

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:text="center"
        android:textSize="8dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>
        
    <TextView
        android:text="center\nvertical"
        android:textSize="8dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"/>

    <TextView
        android:text="center\nhorizontal"
        android:textSize="8dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"/>

    <TextView
        android:text="end"
        android:textSize="8dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end"/>

    <TextView
        android:text="bottom"
        android:textSize="8dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"/>

</FrameLayout>

使いどころ

  • 子ビューを重ねて表示したい場合には有効。
  • かつては、LinearLayoutRelativeLayoutforeground属性をサポートしていなかったため、タップ時にビューの色を変えるオーバーレイ表示など、foregroundを利用する際に唯一の選択肢となっていた。

参考

最終更新: 2025.9.7