android-studio
  1. android-studio-fragments

Android Studio Fragments

Fragments are one of the most important components of an Android app. A fragment represents a part of the user interface of the app. It can be combined with other fragments to form a complete user interface. With fragments, you can create reusable and modular user interface components.

Syntax

class MyFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.my_fragment, container, false)
    }
}

Example

Let's create a simple example of a fragment that displays a text message.

class MyFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.my_fragment, container, false)

        // Find the TextView in the layout
        val textView : TextView = view.findViewById(R.id.text_view)

        // Set the text of the TextView
        textView.text = "Hello, Fragment!"

        // Return the inflated layout
        return view
    }
}

Output

When the above fragment is added to an activity, it will display the text "Hello, Fragment!" on the screen.

Explanation

The onCreateView() method is called when the fragment is being created. In this method, we inflate the layout for the fragment and return the inflated view. We can then find views in the layout using findViewById() and modify them as necessary.

Use

Fragments are commonly used to create reusable user interface components that can be combined with other fragments to form a complete user interface. They are often used in conjunction with a ViewPager, which allows users to swipe between multiple fragments.

Important Points

  • Fragments are reusable and modular user interface components that can be combined with other fragments to form a complete user interface.
  • onCreateView() is called when the fragment is being created. In this method, we inflate the layout for the fragment and return the inflated view.
  • Fragments can be added to an activity using a FragmentManager.
  • Fragments can communicate with each other using a ViewModel.

Summary

Fragments are an important component of an Android app that allows developers to create reusable and modular user interface components. They can be combined with other fragments to form a complete user interface. The onCreateView() method is used to create the user interface for the fragment, and fragments can communicate with each other using a ViewModel.

Published on: