Android/Java การเพิ่ม/ลบ Fragment ด้วย BackStack 2

เมื่อเรียก Fragment ไว้หลายอัน เวลากดปุ่ม Back ย้อนกลับ จะย้อนกลับตามลำดับ Stack

สร้าง Fragment ขึ้นมาใหม่ชื่อ FirstFragmentSecondFragment และ ThirdFragment

ไฟล์ที่เกี่ยวข้อง

  • activity_main.xml
  • MainActivity.java
  • fragment_first.xml
  • FirstFragment.java
  • fragment_second.xml
  • SecondFragment.java
  • fragment_third.xml
  • ThirdFragment.java

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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">

    <GridLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="10dp">

        <Button
            android:id="@+id/button1"
            android:text="Fragment 1"
            android:textSize="16sp" />

        <Button
            android:id="@+id/button2"
            android:text="Fragment 2"
            android:textSize="16sp" />

        <Button
            android:id="@+id/button3"
            android:text="Fragment 3"
            android:textSize="16sp" />
    </GridLayout>

    <Button
        android:id="@+id/buttonClose"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="10dp"
        android:text="Close Current Fragment"
        android:textAllCaps="false"
        android:textSize="18sp" />

    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

MainActivity.java

package com.phaisarn.myapplication;

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

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

public class MainActivity extends AppCompatActivity {

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

        final FirstFragment f1 = new FirstFragment();
        final SecondFragment f2 = new SecondFragment();
        final ThirdFragment f3 = new ThirdFragment();
        final FragmentManager fragMan = getSupportFragmentManager();

        Button button1 = findViewById(R.id.button1);
        Button button2 = findViewById(R.id.button2);
        Button button3 = findViewById(R.id.button3);
        Button buttonClose = findViewById(R.id.buttonClose);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                replaceFragment(f1);
            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                replaceFragment(f2);
            }
        });

        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                replaceFragment(f3);
            }
        });

        buttonClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fragMan.popBackStack();
                Toast.makeText(getApplication(), "popBackStack", Toast.LENGTH_SHORT).show();
            }
        });

        fragMan.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
            @Override
            public void onBackStackChanged() {
                if (fragMan.getBackStackEntryCount() == 0) {
                    finish();    //close activity
                }
            }
        });
    }

    private void replaceFragment(Fragment fragment) {
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.frameLayout, fragment)
                .addToBackStack(null)
                .commit();
    }
}

บรรทัดที่ 54 เมื่อมีการกดปุ่ม buttonClose ไม่ว่าจะมี fragment ให้ปิดหรือไม่ ก็จะทำการ Toast ออกมา
บรรทัดที่ 61 เมื่อจำนวน fragment ใน BackStack เท่ากับ 0 ก็ให้ปิด Activity นี้เลย

fragment_first.xml

<?xml version="1.0" encoding="utf-8"?>
<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:background="#cde"
    android:orientation="vertical"
    tools:context=".FirstFragment">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_margin="30dp"
        android:text="Fragment #1"
        android:textSize="20sp" />
</LinearLayout>

FirstFragment.java

package com.phaisarn.myapplication;


import android.os.Bundle;

import androidx.fragment.app.Fragment;

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


/**
 * A simple {@link Fragment} subclass.
 */
public class FirstFragment extends Fragment {


    public FirstFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false);
    }

}

fragment_second.xml

<?xml version="1.0" encoding="utf-8"?>
<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:background="#ebe"
    android:orientation="vertical"
    tools:context=".SecondFragment">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_margin="30dp"
        android:text="Fragment #2"
        android:textSize="20sp" />

</LinearLayout>

SecondFragment.java

package com.phaisarn.myapplication;


import android.os.Bundle;

import androidx.fragment.app.Fragment;

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


/**
 * A simple {@link Fragment} subclass.
 */
public class SecondFragment extends Fragment {


    public SecondFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_second, container, false);
    }

}

fragment_third.xml

<?xml version="1.0" encoding="utf-8"?>
<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:background="#fbb"
    android:orientation="vertical"
    tools:context=".ThirdFragment">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_margin="30dp"
        android:text="Fragment #3"
        android:textSize="20sp" />

</LinearLayout>

ThirdFragment.java

package com.phaisarn.myapplication;


import android.os.Bundle;

import androidx.fragment.app.Fragment;

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


/**
 * A simple {@link Fragment} subclass.
 */
public class ThirdFragment extends Fragment {


    public ThirdFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_third, container, false);
    }

}