見出し画像

『Android』 - コード内での動的Fragment操作 (動的)


概要

前回の「Fragmentの基本的な使い方(静的ロード)」では、レイアウトファイル内でFragmentを直接追加する方法を説明しました。今回は、**最新のAndroid APIやライブラリ(2025年現在)**を使用し、コード内でFragmentを動的に操作する方法を解説します。

動的ロードを活用することで、必要な画面の表示を柔軟に制御でき、複雑なUI要件にも対応可能です。


最新のFragmentManager操作方法

2025年のAndroidでは、JetpackライブラリとAndroidXを使用することが推奨されます。以下に最新のFragment操作のコード例を示します。

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity {
    private FragmentA fragmentA;
    private FragmentB fragmentB;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fragmentA = new FragmentA();
        fragmentB = new FragmentB();

        // 初期Fragmentの設定
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragment_container, fragmentA, "FragmentA")
                    .commit();
        }
    }

    // Fragmentを切り替えるメソッド
    public void switchToFragmentB(String name, String phone, String address) {
        fragmentB.setResult(name, phone, address);
        getSupportFragmentManager().beginTransaction()
                .setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
                .replace(R.id.fragment_container, fragmentB, "FragmentB")
                .addToBackStack(null)
                .commit();
    }

    // FragmentAに戻る
    public void backToFragmentA() {
        getSupportFragmentManager().popBackStack();
    }
}

XMLレイアウト
FragmentContainerViewを使うことで、Jetpack Navigationともシームレスに連携可能です。

<androidx.fragment.app.FragmentContainerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Fragmentの実装例

FragmentA.java

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class FragmentA extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_a, container, false);
    }
}

FragmentB.java

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class FragmentB extends Fragment {
    private Button btnBackToFragmentA;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_b, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        btnBackToFragmentA = view.findViewById(R.id.btn_back_to_fragment_a);
        btnBackToFragmentA.setOnClickListener(v -> {
            if (getActivity() instanceof MainActivity) {
                ((MainActivity) getActivity()).backToFragmentA();
            }
        });
    }

    public void setResult(String name, String phone, String address) {
        // TODO: FragmentBにデータを反映させる処理
    }
}

ポイント

  • FragmentManagerを利用することで、柔軟な画面操作が可能です。

  • Activity内で定義したパブリックメソッドは、Fragmentから直接呼び出すことができます。


Fragmentの切り替えアニメーション

FragmentTransactionのsetCustomAnimationsメソッドを活用して、切り替え時のアニメーションを指定します。

transaction.setCustomAnimations(
    android.R.anim.slide_in_left,  // 入るときのアニメーション
    android.R.anim.slide_out_right // 出るときのアニメーション
);

主な変更点(2015年版との違い)

  1. FragmentManagerの変更:

    • getFragmentManager()からgetSupportFragmentManager()に変更(AndroidX対応)。

  2. FragmentContainerViewの利用:

    • FrameLayoutではなくFragmentContainerViewを推奨。

  3. ライフサイクルメソッドの改善:

    • onActivityCreatedは廃止され、onViewCreatedを使用。

  4. アニメーションの簡略化:

    • android.R.animを使用して、基本的なアニメーションを簡単に指定。


まとめ

  • 最新のAndroid開発では、AndroidXJetpackライブラリを活用することで、より簡潔でメンテナンス性の高いコードが実現できます。

  • FragmentContainerViewやgetSupportFragmentManagerの使用を標準とし、過去のコードからの移行を推奨します。

次回は、Navigation Componentを使用した複雑な画面遷移の実装方法を解説します。

いいなと思ったら応援しよう!