SoFunction
Updated on 2025-04-07

Detailed explanation of how to use fragments in Android

Use of Fragment

In fact, fragments are very simple, but there are too many blog posts that are randomly charged online, so sometimes we feel that they are messy. Today, let’s briefly explain the use of fragments.
There are two types of fragments: static addition of fragments and dynamic addition of fragments. Let’s first take a look at how to implement static addition of fragments.

Static addition of fragments

First, build two Layout files first, which is the fragment layout file. You may have discovered that Android Studio can directly and quickly create fragments, just like Activity, but this will generate a lot of useless code, so we still choose to create fragment layout ourselves.

Both layouts are very simple, there is only a centered TextView inside, so the code is posted below.

The first layout file:fragment_first.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:andro
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_blue_light"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="This is the first fragment!"/>
</LinearLayout>

The second layout filefragment_second.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:andro
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_green_light"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="This is the second fragment!"/>
</LinearLayout>

Now that the layout file is built, it is time for us to create their corresponding Fragment, that is, the background code. Create two new classes, called FirstFragment and SecondFragment, both inherit from Fragment. One thing to note is that all the Fragments used in our tutorial are. This package is more conducive to program compatibility.

It is also very simple to post the code of the two classes. It just rewrites the onCreateView method to load different layout files.

public class FirstFragment extends Fragment {
private View view;//Get the layout file corresponding to the fragments for easy subsequent use//Remember to rewrite the onCreateView method@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = (.fragment_first, container, false);//Get the corresponding layout filereturn view;
}
}
public class SecondFragment extends Fragment {
private View view;//Get the layout file corresponding to the fragments for easy subsequent use//Remember to rewrite the onCreateView method@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = (.fragment_second, container, false);//Get the corresponding layout filereturn view;
}
}

OK, we have finished the basic work, and now we use two activities to show how to add fragments statically and dynamically.

To add a control statically, you need to use the fragment control and specify that its name is the Fragment you just created. Let's take a look.

Let’s first post the layout of the first activity:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:andro
xmlns:tools="/tools"
android:
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="">
<fragment
android:
android:name=""
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"></fragment>
<fragment
android:
android:name=""
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"></fragment>
<Button
android:
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="Go to next page"
android:textAllCaps="false"/>
</LinearLayout>


That button is used to jump to the next interface, that is, the activity of dynamically adding fragmented cases, which can be ignored here.

Here we see that the two fragments specify the name of FirstFragment and SecondFragment respectively, which is the two fragments you just created. Remember to add the package name. By the way, there is another problem, that is, there is no preview. If you want to preview, you need to add a code to the fragment tag:

Tools:layout="@layout/Layout File Name"  .

Okay, statically adding fragments is done, what? It's that simple, right...it's that simple.

Dynamically add fragments

We don’t need to use the fragment control to dynamically add fragments, but we need to use a FrameLayout control. Why is this? First of all, we all know that the controls in FrameLayout start from the upper left corner, without position control. Dynamically adding fragments is actually adding fragments to the container dynamically, and fragment control can only be used to statically bind a fragment.

Let’s first post the layout of the second activity:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:andro
xmlns:tools="/tools"
android:
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Load First!"
android:textAllCaps="false"/>
<Button
android:
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Load Second!"
android:textAllCaps="false"/>
<FrameLayout
android:
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>

The two buttons above are used to load different fragments, while theFrameLayoutIt is the container for fragment display.

Without further ado, post code:

import .;
import .;
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
(savedInstanceState);
setContentView(.activity_second);

//Load the first fragment when clicking the first buttonfindViewById(.second_btnLoadFirst).setOnClickListener(new () {
@Override
public void onClick(View view) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = ();
(.second_fl, new FirstFragment());
();
}
});
//Load the second fragment when clicking the second buttonfindViewById(.second_btnLoadSecond).setOnClickListener(new () {
@Override
public void onClick(View view) {
getSupportFragmentManager().beginTransaction().replace(.second_fl, new SecondFragment()).commit();//Abbreviation}
});
}
}

The getSupportFragmentManager method is used to obtain a fragment manager object (when using this method, please note that it is the packaged one), and then start a fragmented thing object through this method. This object is more critical and can be used to dynamically add fragments. Call its replace method, which will clear all other controls in the specified container, and then add new fragments. Here, first clear the controls in second_f1, and then add a FirstFragment to enter.

After the replacement, remember to call the commit method to submit, otherwise all your operations will not take effect. Remember.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.