Androidにおけるフラグメントの実装と管理

フラグメントは、アプリケーションのページ遷移として機能し、小型のアクティビティと見なすことができます。その実装プロセスは、main_activityのXML内にFragment用のレイアウトを定義し、このレイアウトにフラグメントを配置することです。次に、このページにIDを設定し、主アクティビティ内でクリックリスナーイベントを通じて、作成したフラグメントをフラグメントトランザクション管理のreplace関数を使って指定されたフラグメント領域に配置します。実装コードは以下の通りです:main_activity.xml ```

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity">

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/switch_btn"
    android:text="@string/switch_fragment"/>

<Button
    android:id="@+id/replace_btn"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/replace_fragment" />

   <FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/fragment_container"
    android:background="@color/design_default_color_primary">

</FrameLayout>

フラグメントファイルの実装:

package com.example.androidfragments;

import android.content.Context;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.util.Log;

public class SampleFragment extends Fragment {

    private static final String LOG_TAG = "SampleFragment";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            String data = bundle.getString("content");
            Log.d(LOG_TAG, "Received data: " + data);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // フラグメントのレイアウトをインフレート
        return inflater.inflate(R.layout.layout_sample_fragment, container, false);
    }
}

メインアクティビティ:

package com.example.androidfragments;

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

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Button switchButton;
    private Button replaceButton;
    private FragmentManager fragmentManager;

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

    private void initializeViews() {
        switchButton = findViewById(R.id.switch_btn);
        replaceButton = findViewById(R.id.replace_btn);
        fragmentManager = getSupportFragmentManager();
    }

    private void setupClickListeners() {
        switchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("content", "Sample Data");
                SampleFragment sampleFragment = new SampleFragment();
                sampleFragment.setArguments(bundle);
                displayFragment(sampleFragment);
            }
        });

        replaceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                displayFragment(new ContentFragment());
            }
        });
    }

    private void displayFragment(Fragment fragment) {
        // フラグメントマネージャーを取得
        // トランザクションを開始
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        
        // 指定されたコンテナにフラグメントを配置
        transaction.replace(R.id.fragment_container, fragment);
        
        // バックスタックに追加して、戻る操作を実現
        transaction.addToBackStack(null);
        
        // トランザクションをコミット
        transaction.commit();
    }
}

タグ: Android フラグメント Fragment管理 UI実装 アプリ開発

8月20日 01:39 投稿