Sobes.tech
Junior — Middle

What is the purpose and application of fragments in application development?

sobes.tech AI

Answer from AI

Fragments in Android are modular parts of the user interface that can be used within an Activity. They allow for creating flexible and reusable UI components.

Purpose and application:

  • They enable dividing the interface into independent parts that can be dynamically added, replaced, or removed.
  • They simplify support and scaling of the application.
  • They provide interface adaptability for different screen sizes (for example, on tablets, multiple fragments can be shown simultaneously).

Example of usage:

class ExampleFragment : Fragment() {
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_example, container, false)
    }
}

In an Activity, a fragment can be added programmatically:

supportFragmentManager.beginTransaction()
    .replace(R.id.fragment_container, ExampleFragment())
    .commit()