SoFunction
Updated on 2025-04-07

Android Fragment source code analysis Add method

Preface

In this article, we will talk about the Add() method in Fragment management

Add()

In our dynamic addition and management of Fragments, Add is the most basic method; the usage is also very simple, as follows: Add a Fragment to the Activity:

getSupportFragmentManager().beginTransaction().add(,new FragmentA()).commit();

Generally speaking, when we use Fragment, there are more than one, such as the WeChat interface, where there are four buttons at the bottom navigation, corresponding to four different Fragments. If we switch the interface every time the bottom button is clicked, we can use Add() plus hide and show to combine it.

Let's implement it briefly, here we will make two fragments.

Here our MainActivity layout is as follows:

<LinearLayout xmlns:andro
    xmlns:tools="/tools"
    android:
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="">
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:/>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android: 
            android:text="FragmentA"
            android:layout_width="0dp"
            android:layout_height="match_parent" 
            android:layout_weight="1"/>
        <Button
            android:
            android:text="FragmentB"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"/>
    </LinearLayout>
</LinearLayout>

Let’s see the content of MainActivity:

package ;
import .;
import .;
import .;
import .;
import ;
import ;
import ;
import ;
import ;
import ;
public class MainActivity extends AppCompatActivity implements {
private String  TAG=();
    private Button fragmentA_Button;
    private Button fragmentB_Button;
private FragmentTransaction transaction;
    private FragmentManager fragmentManager;
    private Fragment fragment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        (savedInstanceState);
        (TAG,"onCreate--executed");
        setContentView(.activity_main);
        fragmentManager=getSupportFragmentManager();
        transaction=  ();
        fragment=new FragmentA();
        (,fragment,"FragmentA").commit();
        fragmentA_Button=(Button) findViewById(.fragmenta_button);
        fragmentB_Button=(Button) findViewById(.fragmentb_button);
        fragmentA_Button.setOnClickListener(this);
        fragmentB_Button.setOnClickListener(this);
    }
    @Override
    protected void onStart() {
        ();
        (TAG,"onStart--executed");
    }
    @Override
    protected void onResume() {
        ();
        (TAG,"onResume--executed");
    }
    @Override
    protected void onPause() {
        ();
        (TAG,"onPause--executed");
    }
    @Override
    protected void onStop() {
        ();
        (TAG,"onStop--executed");
    }
    @Override
    protected void onDestroy() {
        ();
        (TAG,"onDestroy--executed");
    }
    @Override
    public void onClick(View v) {
        transaction=  ();
        switch (()){
            case .fragmenta_button:
                if (fragment!=null)
                    (fragment);
                fragment=  ("FragmentA");
                if (fragment!=null){
                    (fragment);
                }
                else {
                    fragment=new FragmentA();
                    (,fragment,"FragmentA").commit();
                }
                break;
           case .fragmentb_button:
                if (fragment!=null)
                    (fragment);
            fragment=  ("FragmentB");
                if (fragment!=null){
                    (fragment);
                }
                else {
                    fragment=new FragmentB();
                    (,fragment,"FragmentB").commit();
                }
                break;
        }
    }
}

What we wrote here is relatively simple, mainly to see their execution life cycle. Here I printed out all the logs.

The log at the beginning of the run is as follows:

I/MainActivity: onCreate--execute
I/FragmentA: onAttach--executed
I/FragmentA: onCreate--executed
I/FragmentA: onCreateView--executed
I/FragmentA: onActivityCreated--executed
I/FragmentA: onStart--executed
I/MainActivity: onStart--executed
I/MainActivity: onResume--execute
I/FragmentA: onResume--execute

At this time, we click the FragmentB button;

I/FragmentB: onAttach--executed
I/FragmentB: onCreate--execute
I/FragmentB: onCreateView--executed
I/FragmentB: onActivityCreated--executed
I/FragmentB: onStart--executed
I/FragmentB: onResume--execute

Then we repeatedly clicked the FragmentA and FragmentB buttons and found that there was no log print. At this time, it was proved that when FragmentA and FragmentB switched through hide and show methods, they will only be initialized once.

Let's look at the method of replace

replace:

First of all, the replace method is actually a combination of remove and add methods; remove means to delete a Fragment from the FragmentManager. If we switch to the next Fragment, the previous Fragment is no longer needed, and you can use replace directly. If we still need it, the corresponding method is also provided in the API, which is to add the fallback stack to addToBackStack()

Let's change the code in MainActivity:

  @Override
    public void onClick(View v) {
        transaction=  ();
        switch (()){
            case .fragmenta_button:
                if (fragment!=null)
                    (fragment);
                fragment=  ("FragmentA");
                if (fragment!=null){ (TAG,"fragment is not empty");
                    (fragment);
                }
                else {
                    (TAG,"fragment is empty");
                    fragment=new FragmentA();
                    (,fragment,"FragmentA").addToBackStack("FragmentA").commit();
                }
                break;
           case .fragmentb_button:
                if (fragment!=null)
                    (fragment);
            fragment=  ("FragmentB");
                if (fragment!=null){
                    (TAG,"fragment is not empty");
                    (fragment);
                }
                else {
                    (TAG,"fragment is empty");
                    fragment=new FragmentB();
                    (,fragment,"FragmentB").addToBackStack("FragmentB").commit();
                }
                break;
        }
        }

Here we have changed the code in OnClick, and then we will print the log and take a look:

First, it is consistent when initializing:

Write a code piece here

At this time, we click FragmentB:

12-18 21:48:14.227 21081-21081/ I/MainActivity: fragment is empty
12-18 21:48:14.228 21081-21081/ I/FragmentA: onPause--executed
12-18 21:48:14.228 21081-21081/ I/FragmentA: onStop--executed
12-18 21:48:14.228 21081-21081/ I/FragmentA: onDestroyView--executed
12-18 21:48:14.229 21081-21081/ I/FragmentB: onAttach--executed
12-18 21:48:14.229 21081-21081/ I/FragmentB: onCreate--executed
12-18 21:48:14.250 21081-21081/ I/FragmentB: onCreateView--executed
12-18 21:48:14.250 21081-21081/ I/FragmentB: onActivityCreated--executed
12-18 21:48:14.250 21081-21081/ I/FragmentB: onStart--executed
12-18 21:48:14.250 21081-21081/ I/FragmentB: onResume--executed

We found that Fragment called destroy method, and then we click FragmentA:

I/MainActivity: fragment is not empty

At this time, we found that FragmentA did not switch over. This is because we found an instance of FragmentA in the FragmentManager. However, at this time, the interface of FragmentA has been destroyed, so what we see is FragmentB. At this time, our OnClick is changed to the following:

   @Override
    public void onClick(View v) {
        transaction=  ();
        switch (()){
            case .fragmenta_button:
                    fragment=new FragmentA();
                    (,fragment,"FragmentA").addToBackStack("FragmentA").commit();
                break;
           case .fragmentb_button:
                    fragment=new FragmentB();
                    (,fragment,"FragmentB").addToBackStack("FragmentB").commit();
                break;
        }
    }

Print the log again at this time.

12-18 21:48:14.228 21081-21081/ I/FragmentA: onPause--executed
12-18 21:48:14.228 21081-21081/ I/FragmentA: onStop--executed
12-18 21:48:14.228 21081-21081/ I/FragmentA: onDestroyView--executed
12-18 21:48:14.229 21081-21081/ I/FragmentB: onAttach--executed
12-18 21:48:14.229 21081-21081/ I/FragmentB: onCreate--executed
12-18 21:48:14.250 21081-21081/ I/FragmentB: onCreateView--executed
12-18 21:48:14.250 21081-21081/ I/FragmentB: onActivityCreated--executed
12-18 21:48:14.250 21081-21081/ I/FragmentB: onStart--executed
12-18 21:48:14.250 21081-21081/ I/FragmentB: onResume--executed

12-18 21:48:14.228 21081-21081/ I/FragmentB: onPause--executed
12-18 21:48:14.228 21081-21081/ I/FragmentB: onStop--executed
12-18 21:48:14.228 21081-21081/ I/FragmentB: onDestroyView--executed
12-18 21:48:14.229 21081-21081/ I/FragmentA: onAttach--executed
12-18 21:48:14.229 21081-21081/ I/FragmentA: onCreate--executed
12-18 21:48:14.250 21081-21081/ I/FragmentA: onCreateView--executed
12-18 21:48:14.250 21081-21081/ I/FragmentA: onActivityCreated--executed
12-18 21:48:14.250 21081-21081/ I/FragmentA: onStart--executed
12-18 21:48:14.250 21081-21081/ I/FragmentA: onResume--executed

At this time, I found that every time I switch, Fragment will be called and all methods of onCreateView() to onDestroyView() will be called again. In fact, it is the entire process of destroying and reconstruction of the layout layer of the Fragment.

Note: When we nest Fragment, if we click the return key and do not want to go back to the previous Fragment, but want to go back to the previous or the forward Fragment, we can use the (String tag, int flags) method to pop up the Fragment with TAG as tag, and at the same time pop up all the Fragments above this Fragment (pop up the fallback stack, that is, completely destroyed, detach)

This is the end of this article about Android Fragment source code analysis Add method. For more related Android Fragment content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!