Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 1 year has passed since last update.

【Andoroid】フラグメントマネージャーのすゝめ①【FragmentManager】

Last updated at Posted at 2024-01-17

FragmentManagerについてまとめてみました。
長くなるので何回かに分けます。。。

FragmentManagerとは?

FragmentManagerとは、Androidアプリでフラグメントを管理するためのクラスです。
動的に画面を変更したり、異なるフラグメントを組み合わせて柔軟なUIを構築することを実現できます。

前準備

トランザクションの開始

トランザクションとは一連の処理をまとめ、それを一括で処理するための単位です。
fragmentManagerを使ったフラグメント管理には、まずトランザクションを開始する必要があります。
beginTransaction メソッドを使用することでトランザクションを開始できます。

val fragmentManager = supportFragmentManager
//フラグメントのトランザクションのインスタンスを取得
val fragmentTransaction = fragmentManager.beginTransaction()

フラグメント管理

トランザクションが開始出来たら、フラグメントの管理をすることができます。
今回は、一番シンプルなフラグメントの追加・削除・置換について紹介します。

フラグメントの追加(add)

addメソッドを使うことでフラグメントを追加することができます。
add メソッドは新しいフラグメントを追加するため、同じコンテナに既に表示されているフラグメントがある場合は、新しいフラグメントが上に重ねられる形で表示されます

val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
// 第一引数 R.id.containerはフラグメントを表示するレイアウトコンテナのID
// 第二引数 上に重ねるFragment
fragmentTransaction.add(R.id.container, fragment()) 

フラグメントの削除(remove)

removeメソッドを使うことでフラグメントを削除することができます。
削除されることでUIからの表示が消えます。
またそれに関連するUIコンポーネントも画面から消えます。

val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
val fragment = fragmentManager.findFragmentById(R.id.container)
    //
fragment?.let {
    fragmentTransaction.remove(it)
}
fragmentTransaction.commit()

フラグメントの置換(replace)

replaceメソッドを使うことでフラグメントの置換をすることができます。
指定されたコンテナ内の現在のフラグメントを取り除き、新しいフラグメントを追加します。

 val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
//第一引数 置き換わる元になるコンテナID
//第二引数 新しくUIに表示したいフラグメント
transaction.replace(R.id.container, newFragment)
fragmentTransaction.commit()

トランザクションのコミット

一番最後にfragmentTransaction.commit()というメソッドがありましたよね。
フラグメントの追加や削除、置換を行うには最後にコミットする必要があります。
トランザクションをcommitメソッドで確定させ、フラグメントの変更を実際に適用します。

fragmentTransaction.commit()

最後に

FragmentManagerを使った、フラグメントの管理について学べました。
開発をしていて疑問に思っていたので少~しすっきりしました。

0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?