Webエンジニアのメモ帳

技術的な話を中心に書いています。

【Android】FragmentContainerViewを画面全体に表示し、上下の余白を無くす方法

Androidの開発でFragmentを使う場合、以下のコードのようにビューにフラグメントを表示する領域を用意しておき、そこにフラグメントを埋め込むような使い方が一般的かと思います。

・MainActivity.kt

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val fragment = MainFragment.newInstance()
        val transaction: FragmentTransaction = supportFragmentManager.beginTransaction()
        transaction.add(R.id.fragment_container, fragment)
        transaction.commit()
    }
}

・activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".activity.MainActivity">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

こちらのコードを実行すると、画面全体にfragment_containerというidで指定した領域が作られ、その中にMainFragmentの内容が表示されます。

ところで、多くの初心者向けのコードでは、フラグメント (FragmentContainerView) が画面全体ではなく画面の中央あたりに表示され、上下に余白が存在するものがほとんどです。 今回のコードのように、ConstraintLayoutを使ってFragmentContainerViewに制約を設けていてもです。

これを回避するには、このコードのようにFragmentContainerViewに以下を指定すればOKです。

android:layout_height="0dp"

こう書くことで、FragmentContainerViewを画面全体に表示させ、上下に意図しない余白が生じるのを防ぐことができます。