7) Setting fragment backstack and popbackstack

MainActivity.java

package com.jamesfroggatt.fragmenttransactiondemo.app;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements FragmentManager.OnBackStackChangedListener{

    FragmentManager manager;
    TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        manager=getFragmentManager();
        text= (TextView) findViewById(R.id.message);
        manager.addOnBackStackChangedListener(this);
    }

    public void addA(View v){

        // create object of the fragment
        FragmentA f1 = new FragmentA();
        // reference to our fragment manager
        FragmentTransaction transaction=manager.beginTransaction();
        transaction.add(R.id.group,f1,"A");

        // ADD TRANSACTION TO THE BACKSTACK BEFORE COMMITTING THE TRANSACTION
        transaction.addToBackStack("addA");

        transaction.commit();
    }

    public void addB(View v){

        // create object of the fragment
        FragmentB f2 = new FragmentB();
        // reference to our fragment manager
        FragmentTransaction transaction=manager.beginTransaction();
        transaction.add(R.id.group,f2,"B");

        // ADD TRANSACTION TO THE BACKSTACK BEFORE COMMITTING THE TRANSACTION
        transaction.addToBackStack("addB");

        transaction.commit();

    }

    public void removeA(View v){

        // we can only remove A if it's there so we have to find fragment A
        FragmentA f1= (FragmentA) manager.findFragmentByTag("A");

        FragmentTransaction transaction=manager.beginTransaction();
        // we need to check if it's there or not before doing the transaction
        // so we don't crash the app if it's not there
        if (f1!=null) {
            transaction.remove(f1);

            // ADD TRANSACTION TO THE BACKSTACK BEFORE COMMITTING THE TRANSACTION
            transaction.addToBackStack("removeA");

            transaction.commit();
        } else {
             Toast.makeText(this,"Fragment A was not added before",Toast.LENGTH_SHORT).show();
        }
    }

    public void removeB(View v){

        // we can only remove A if it's there so we have to find fragment A
        FragmentB f2= (FragmentB) manager.findFragmentByTag("B");

        FragmentTransaction transaction=manager.beginTransaction();
        // we need to check if it's there or not before doing the transaction
        // so we don't crash the app if it's not there
        if (f2!=null) {
            transaction.remove(f2);

            // ADD TRANSACTION TO THE BACKSTACK BEFORE COMMITTING THE TRANSACTION
            transaction.addToBackStack("removeB");

            transaction.commit();
        } else {
            Toast.makeText(this,"Fragment B was not added before",Toast.LENGTH_SHORT).show();
        }
    }

    public void replaceAwithB(View v){

        FragmentB f2= new FragmentB();
        FragmentTransaction transaction=manager.beginTransaction();
        transaction.replace(R.id.group,f2,"B");

        // ADD TRANSACTION TO THE BACKSTACK BEFORE COMMITTING THE TRANSACTION
        transaction.addToBackStack("replaceAwithB");

        transaction.commit();
    }

    public void replaceBwithA(View v){

        FragmentA f1= new FragmentA();
        FragmentTransaction transaction=manager.beginTransaction();
        transaction.replace(R.id.group,f1,"A");

        // ADD TRANSACTION TO THE BACKSTACK BEFORE COMMITTING THE TRANSACTION
        transaction.addToBackStack("replaceBwithA");

        transaction.commit();
    }

    public void attachA(View v){

        FragmentA f1= (FragmentA) manager.findFragmentByTag("A");
        FragmentTransaction transaction=manager.beginTransaction();
        if (f1!=null) {
            transaction.attach(f1);

            // ADD TRANSACTION TO THE BACKSTACK BEFORE COMMITTING THE TRANSACTION
            transaction.addToBackStack("attachA");

            transaction.commit();
        }

    }

    public void detachA(View v){

        FragmentA f1= (FragmentA) manager.findFragmentByTag("A");
        FragmentTransaction transaction=manager.beginTransaction();
        if (f1!=null) {
            // detach just HIDES the fragment, it doesn't destroy it completely
            // only onPause(), onStop(), onDestroy() are called
            transaction.detach(f1);

            // ADD TRANSACTION TO THE BACKSTACK BEFORE COMMITTING THE TRANSACTION
            transaction.addToBackStack("detachA");

            transaction.commit();
        }
    }

    public void back(View v){
        manager.popBackStack();
    }

    public void popAddB(View v){

        // removes all the recent transactions down the the addB transaction
        manager.popBackStack("addB",0);

        // removes all the recent transactions down the the addB transaction INCLUDING the add B
        // transaction
        //manager.popBackStack("addB",FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }

    @Override
    public void onBackStackChanged() {

        text.setText(text.getText()+"\n");
        text.setText(text.getText()+" Current status of the backstack: \n");

        int count=manager.getBackStackEntryCount();
        for (int i=count-1; i>=0; i--){
            FragmentManager.BackStackEntry entry=manager.getBackStackEntryAt(i);
            text.setText(text.getText()+" "+entry.getName()+" \n");
        }
        text.setText(text.getText()+"\n");
    }
}

FragmentA.java

package com.jamesfroggatt.fragmenttransactiondemo.app;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FragmentA extends Fragment {


    @Override
    public void onAttach(Activity activity) {
        Log.d("James","Fragment A onAttach");
        super.onAttach(activity);

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.d("James","Fragment A onCreate");
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_a, container, false);
        Log.d("James","Fragment A onCreateView");
        return view;

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d("James","Fragment A onActivityCreated");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d("James","Fragment A onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d("James","Fragment A onStop");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d("James","Fragment A onResume");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d("James","Fragment A onDestroyView");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("James","Fragment A onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d("James","Fragment A onDetach");
    }
}

FragmentB.java

package com.jamesfroggatt.fragmenttransactiondemo.app;


import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FragmentB extends Fragment {


    @Override
    public void onAttach(Activity activity) {
        Log.d("James", "Fragment B onAttach");
        super.onAttach(activity);

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.d("James","Fragment B onCreate");
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_b, container, false);
        Log.d("James","Fragment B onCreateView");
        return view;

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d("James","Fragment B onActivityCreated");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d("James","Fragment B onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d("James","Fragment B onStop");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d("James","Fragment B onResume");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d("James","Fragment B onDestroyView");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("James","Fragment B onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d("James","Fragment B onDetach");
    }
}

activity_main.xml

<RelativeLayout 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"
    tools:context="${packageName}.${activityClass}">


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="AddA"
        android:onClick="addA"
        android:id="@+id/button"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="RemoveA"
        android:onClick="removeA"
        android:id="@+id/button2"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/button" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ReplaceAwithB"
        android:onClick="replaceAwithB"
        android:id="@+id/button3"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/button2" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="AddB"
        android:onClick="addB"
        android:id="@+id/button4"
        android:layout_below="@+id/button"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="RemoveB"
        android:onClick="removeB"
        android:id="@+id/button5"
        android:layout_alignTop="@+id/button4"
        android:layout_toRightOf="@+id/button4" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ReplaceBwithA"
        android:onClick="replaceBwithA"
        android:id="@+id/button6"
        android:layout_alignTop="@+id/button5"
        android:layout_toRightOf="@+id/button5" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="AttachA"
        android:onClick="attachA"
        android:id="@+id/button7"
        android:layout_below="@+id/button4"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="DetachA"
        android:onClick="detachA"
        android:id="@+id/button8"
        android:layout_alignTop="@+id/button7"
        android:layout_toRightOf="@+id/button7" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="back"
        android:onClick="back"
        android:id="@+id/button9"
        android:layout_below="@+id/button7"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pop Add B"
        android:onClick="popAddB"
        android:id="@+id/button10"
        android:layout_below="@+id/button7"

        android:layout_toRightOf="@+id/button9"/>

    <!-- fragments will be put in this linear layout below -->
    <!-- the linear layout will be the CONTAINER for the fragments -->
   <LinearLayout
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:layout_alignParentRight="true"
       android:layout_below="@+id/button9"
       android:layout_alignParentBottom="true">
    <LinearLayout
        android:orientation="vertical"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:background="#FFeeee"
        android:layout_height="match_parent"
       android:layout_gravity="center"
        android:layout_below="@+id/button10"
        android:id="@+id/group"
        ></LinearLayout>

        <ScrollView
            android:layout_width="0dp"
            android:background="#CCDDFF"
            android:layout_height="match_parent"
            android:layout_weight="1">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=""
                android:id="@+id/message" />

            </ScrollView>


    </LinearLayout>
</RelativeLayout>

fragment_a.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#AA66DD">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#FFF"
        android:text="This is FRAGMENT A"
        android:id="@+id/textView1"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true" />


</LinearLayout>

fragment_b.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFBB00">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000"
        android:text="This is FRAGMENT B"
        android:id="@+id/textView2"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true" />


</LinearLayout>

Notes from Vivz slide nerd videos at youtube

Leave a Reply