【Kotlin/Android Studio】Fragmentを動的に切り替える方法!replaceメソッド

この記事からわかること

  • Android Studio/KotlinFragment動的切り替える方法
  • supportFragmentManagerreplaceメソッド使い方

index

[open]

\ アプリをリリースしました /

みんなの誕生日

友達や家族の誕生日をメモ!通知も届く-みんなの誕生日-

posted withアプリーチ

環境

Fragmentを動的に切り替える方法

Kotlinでボタンのタップなどで動的に表示しているFragmentを切り替えるにはsupportFragmentManagerreplaceメソッドを使用します。

supportFragmentManager.beginTransaction().apply {
    replace(R.id.main_frame, FirstFragment())
    addToBackStack(null)
    commit()
}

実装サンプル

実際にボタンのタップでFragmentが切り替わるコードを実装してみます。

【Kotlin/Android Studio】Fragmentを動的に切り替える方法!replaceメソッド

まずはレイアウト側にFragmentを表示させるためのFrameLayoutと2つのボタンを用意します。


<?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"
    android:id="@+id/container"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/main_frame"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/linearLayout"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </FrameLayout>

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent">

        <Button
            android:id="@+id/first_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="First" />

        <Button
            android:id="@+id/second_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Second" />
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

ロジック部分では以下のようにボタンがタップされた際にFragmentが切り替わるようにしています。


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

        val firstBtn: Button = findViewById(R.id.first_button)
        val secondBtn: Button = findViewById(R.id.second_button)

        firstBtn.setOnClickListener{
            supportFragmentManager.beginTransaction().apply {
                replace(R.id.main_frame, FirstFragment())
                addToBackStack(null)
                commit()
            }
        }

        secondBtn.setOnClickListener{
            supportFragmentManager.beginTransaction().apply {
                replace(R.id.main_frame, SecondFragment())
                addToBackStack(null)
                commit()
            }
        }
    }
}

まだまだ勉強中ですので間違っている点や至らぬ点がありましたら教えていただけると助かります。

ご覧いただきありがとうございました。

searchbox

スポンサー

ProFile

ame

趣味:読書,プログラミング学習,サイト制作,ブログ

IT嫌いを克服するためにITパスを取得しようと勉強してからサイト制作が趣味に変わりました笑
今はCMSを使わずこのサイトを完全自作でサイト運営中〜

New Article

index