SoFunction
Updated on 2025-04-05

Detailed explanation of the specific usage of Android Fragment

Simple usage of Fragment

  • Add two Fragments in an Activity and let these two Fragments divide the Activity space equally
  • Create a new layout of the Fragment on the left side left_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:
        android:layout_gravity="center_horizontal"
        android:text="Button"/>
</LinearLayout>

Create a layout of the Fragment on the right side right right_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro
    android:orientation="vertical"
    android:background="#00FF00"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textSize="24sp"
        android:text="This is  right fragment"/>
</LinearLayout>
  • Then create a new LeftFragment class and let it inherit the Fragment. There will be two Fragments under the packages provided for us to use.
  • What we want to choose is Fragment in the AndroidX library, because it can keep the features of Fragment consistent across all Android versions.
  • Using the Fragment in the AndroidX library does not require adding additional dependencies to the file. You only need to check the Use androidx.* artifacts option when creating a new project. AS will automatically help import the necessary AndroidX library.
  • LeftFragmeng code
class LeftFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return (.left_fragment, container, false)
    }
}
  • Here we rewritten the onCreateView() method of the Fragment class. In this method, the defined left_fragment.xml layout is dynamically loaded through the inflater() method of LayoutInflater.
  • In the same way, create a RightFragment
class RightFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return (.right_fragment, container, false)
    }
}

Add fragment in activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
    <fragment
        android:
        android:name=""
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />
    <fragment
        android:
        android:name=""
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />
</LinearLayout>

It should be noted that fragment needs to be added to the Fragment class name through the android:name attribute. It should be noted that the package name of the class must be added as well.

Dynamically add Fragment

  • The real power of Fragment is that it can be dynamically added to the Activity when the program is running, and dynamically add Fragment according to specific circumstances, making the program customization diversified.
  • Create another_right_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFF00"
    android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="This is another right fragment"
        android:textSize="24sp" />
</LinearLayout>

Create anotherRightFragment class for loading layout

class AnotherRightFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return (.another_right_fragment, container, false)
    }
}

Next, we dynamically add it to the Activity and modify the code in activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
    <fragment
        android:
        android:name=""
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />
    <FrameLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:>
    </FrameLayout>
</LinearLayout>

Add content to FrameLayout in the code, so as to dynamically implement the function of Fragment and modify the code in MainActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        (savedInstanceState)
        setContentView(.activity_main)
        //Use AnotherRightFragment when clicking the button         {
            //Create a Fragment instance and pass in the replaceFragment() method for processing            replaceFragment(AnotherRightFragment())
        }
        //Use RightFragment when you don't click the button to achieve a dynamic effect        replaceFragment(RightFragment())
    }
    private fun replaceFragment(fragment: Fragment) {
        //Call getSupportFragmentManager() method to get fragmentManager        val fragmentManager = supportFragmentManager
        //fragmentManager calls beginTransaction() to start a transaction        val transition = ()
        //Add or fragment to the container        (, fragment)
        //Call commit() method for transaction commit        ()
    }
}

Implementing return stack in Fragment

  • After realizing the function of dynamically adding Fragment to Activity, I found that after clicking the button, I added a Fragment and pressed the return key, the program will exit directly.
  • If we want to achieve an effect similar to the return stack, press the return key to return to the previous Fragment, how to achieve it?
  • In fact, it is very simple. A addToBackStack() is provided in FragmentTransation, which can be used to add a transaction to the return stack.
  • Modify the code in MainActivity to implement this function. You only need to add a line of code to the replaceFragment() method.
    private fun replaceFragment(fragment: Fragment) {
        //Call getSupportFragmentManager() method to get fragmentManager        val fragmentManager = supportFragmentManager
        //fragmentManager calls beginTransaction() to start a transaction        val transition = ()
        //Add or fragment to the container        (, fragment)
        //Add a return stack to the Fragment        //Accept a name to describe the status of the return stack, generally pass null        (null)
        //Call commit() method for transaction commit        ()
    }

Interaction between Fragment and Activity

Although Fragments are embedded in Activity for display, their relationship is not that close

In fact, Activity and Fragment each exist in a separate class, and there is not such an obvious way to interact directly.

In order to facilitate interaction between Fragment and Activity, FragmentManager provides a method similar to findViewById(), which is specifically used to obtain Fragment instances from layout files. The code is as follows

val fragment = () as LeftFragment

Calling the findFragmentById() method of the FragmentManager can get an instance of the response Fragment in the Activity, and then you can easily call the methods in the Fragment.

In addition, similar to findiewById(), the kotlin-android-extensions plug-in also expands the findFragmentById() method, allowing us to directly use the Fragment id name defined in the layout file to automatically obtain the corresponding Fragment instance.

For example:

val fragment = leftFrag as LeftFragment

The related methods of calling Fragment in Activity are as follows

Calling Activity in Fragment is also very simple

In each Fragment, you can use the getActivity() method to obtain the Activity instance associated with the current Fragment

For example:

if (activity != null) {
    val mainActivity = activity as MainActivity
}

This is the introduction to this article about the specific usage of Android Fragment. 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!