Fragment’s two jump methods, with theories and examples

Jump to multiple Fragments

Many software nowadays involve switching between multiple pages. Here you can use Fragment to do it. If you use Fragment to achieve this effect, there will be a problem. Then how to switch between multiple Fragments. Here is an introduction to Fragment There are two switching methods,

In Android, there are two main ways to switch Fragments: using the replace method and using the hide/show method.

replace method – Basically, a Fragment instance will be created every time it is replaced,

 transaction.replace(R.id.fragnment, fragment1);

add-hide-show method-A commonly used method in development, reducing unnecessary overhead`

 transaction.add(R.id.fragnment, fragment1);
 transaction.hide(fragment1);
 transaction.show(fragment2);

Both methods have their own advantages and disadvantages. The first method will completely replace one Fragment with another Fragment, creating a new Fragment each time and destroying the old Fragment, which may waste resources. It seems that the second one is better than the second one. One is good, but as you can guess from the method name, the second method does not destroy the Fargment, it just hides it, so if you have a large number of Fragments that need to be switched, these Fragments will occupy memory, which may cause Memory overflow. In actual development, choose the appropriate method according to actual needs.

Example

Just saying this may not make sense, you may not understand it, and you may not know how to use it. Here is a small example.

In this demo, I will give part of the code (the viewing experience of all the codes is not very good) to facilitate understanding, so

The first is the main activity layout, then a Fragment and layout will be given, and finally the core jump.

Main activity layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white2">
    <LinearLayout
        android:id="@ + id/ll_tab"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal"
        android:layout_alignParentBottom="true">

        <LinearLayout
            android:id="@ + id/fragment1"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_weight="1"
            android:layout_gravity="center"
            android:orientation="horizontal">

            <ImageView
                android:id="@ + id/thid1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/bottom1" />
        </LinearLayout>

        <LinearLayout
            android:id="@ + id/fragment2"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_weight="1"
            android:layout_gravity="center"
            android:orientation="horizontal">

            <ImageView
                android:id="@ + id/thid2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/bottomht2"
                />
        </LinearLayout>

        <LinearLayout
            android:id="@ + id/fragment3"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_weight="1"
            android:layout_gravity="center"
            android:orientation="horizontal">

            <ImageView
                android:id="@ + id/thid3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/bottom3"
                />
        </LinearLayout>

        <LinearLayout
            android:id="@ + id/fragment4"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_weight="1"
            android:layout_gravity="center"
            android:orientation="horizontal">

            <ImageView
                android:id="@ + id/thid4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/bottomht4"
                />
        </LinearLayout>

        <LinearLayout
            android:id="@ + id/fragment5"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_weight="1"
            android:layout_gravity="center"
            android:orientation="horizontal">

            <ImageView
                android:id="@ + id/thid5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/bottomht5"
                />
        </LinearLayout>
    </LinearLayout>

    <FrameLayout
        android:id="@ + id/fl_Demo"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/ll_tab"
        >
    </FrameLayout>
</RelativeLayout>

There is nothing special here. If you want to implement it simply, you can consider replacing ImageView with TextView.

Fragment and layout

public class Fragment1 extends Fragment {<!-- -->
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {<!-- -->

        View view = inflater.inflate(R.layout.fragment1, null);
        return view;
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is an example Fragment1"
        android:textSize="20sp"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="16dp" />

    <Button
        android:id="@ + id/button_toast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Display message 1111" />
</LinearLayout>

Both are featureless

Fragment jump

//Deleted some code for better understanding
public class MainActivity extends AppCompatActivity {<!-- -->

    private LinearLayout m1;//Five buttons
    private LinearLayout m2;
    private LinearLayout m3;
    private LinearLayout m4;
    private LinearLayout m5;

    private ImageView v1;
    private ImageView v2;
    private ImageView v3;
    private ImageView v4;
    private ImageView v5;


    @Override
    protected void onCreate(Bundle savedInstanceState) {<!-- -->
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();//Get each instance
        initState();//Initialize the initial state of the application
        initEvent();//Initialize the click event listener of the view

    }

    //Get each instance
    private void initView() {<!-- -->
        m1 = findViewById(R.id.fragment1);
        m2 = findViewById(R.id.fragment2);
        m3 = findViewById(R.id.fragment3);
        m4 = findViewById(R.id.fragment4);
        m5 = findViewById(R.id.fragment5);
        v1 = findViewById(R.id.thid1);
        v2 = findViewById(R.id.thid2);
        v3 = findViewById(R.id.thid3);
        v4 = findViewById(R.id.thid4);
        v5 = findViewById(R.id.thid5);

    }

    //Initialize application state
    private void initState() {<!-- -->
        // initialization
        FragmentUtils.replaceFragment(MainActivity.this, R.id.fl_Demo,
                new Fragment1());

    }

    //Set the click event, the checkState method has been deleted, its function is to handle the effect of clicking to change the icon;
    private void initEvent() {<!-- -->
        m1.setOnClickListener(new View.OnClickListener() {<!-- -->
            @Override
            public void onClick(View view) {<!-- -->
                FragmentUtils.replaceFragment(MainActivity.this, R.id.fl_Demo,
                        new Fragment1());
                checkState(1);
            }
        });
        m2.setOnClickListener(new View.OnClickListener() {<!-- -->
            @Override
            public void onClick(View view) {<!-- -->
                FragmentUtils.replaceFragment(MainActivity.this, R.id.fl_Demo,
                        new Fragment2());
                checkState(2);
            }
        });
        m3.setOnClickListener(new View.OnClickListener() {<!-- -->
            @Override
            public void onClick(View view) {<!-- -->
                bottomSheetDialog.show();
            }
        });
        m4.setOnClickListener(new View.OnClickListener() {<!-- -->
            @Override
            public void onClick(View view) {<!-- -->
                FragmentUtils.replaceFragment(MainActivity.this, R.id.fl_Demo,
                        new Fragment4());
                checkState(4);
            }
        });
        m5.setOnClickListener(new View.OnClickListener() {<!-- -->
            @Override
            public void onClick(View view) {<!-- -->
                FragmentUtils.replaceFragment(MainActivity.this, R.id.fl_Demo,
                        new Fragment5());
                checkState(5);
            }
        });
    }
}

Maybe you didn’t find the jump-related API I mentioned earlier after reading. Instead, there is an additional FragmentUtils.replaceFragment method. The content in this class is shown below.

public class FragmentUtils {<!-- -->
    public static void replaceFragment(FragmentActivity activity,int viewID,Fragment fragment){<!-- -->
        activity.getSupportFragmentManager().beginTransaction().replace(viewID, fragment).commit();
    }
    public static void show(FragmentActivity activity, int viewID,Fragment fragment){<!-- -->
        activity.getSupportFragmentManager().beginTransaction().add(viewID, fragment).show(fragment).commit();
    }
    public static void hide(FragmentActivity activity,Fragment fragment){<!-- -->
         activity.getSupportFragmentManager().beginTransaction().hide(fragment).commit();
    }
 
}

These methods are preceded by activity.getSupportFragmentManager().beginTransaction() and followed by commit(). Let me explain this first.

activity: This is a FragmentActivity object, which is a subclass of Activity. This instance of FragmentActivity is usually the activity you are currently operating on.

getSupportFragmentManager(): This is a method of FragmentActivity, which returns a FragmentManager object. FragmentManageris used to manage Fragment

beginTransaction: This is a method of FragmentManager that returns a FragmentTransaction object. FragmentTransaction represents a series of Fragment operations that will be combined together and executed as a transaction. Start a new transaction via beginTransaction().

Note here that Fragment operations (such as adding, replacing, hiding, displaying, etc.) are completed through transactions. A transaction can be understood as a series of Fragment operations, which are either all executed or not executed at all.

commit(): All operations in the transaction need to be submitted at the end. The commit() method is called here to submit the transaction. Submitting the transaction means that the operations in the transaction will be executed immediately. If the transaction is not committed, the operations within the transaction will not be executed immediately. This is what the commit() method does.

Above we used the first method to replace, now we use the second method to replace.

//When the Fragment needs to be displayed
FragmentUtils.show(MainActivity.this, R.id.fl_Demo,fragment1); // Show fragment1
FragmentUtils.hide(MainActivity.this, fragment2); // Hide fragment2