Sobes.tech
Junior — Middle

Can you describe the key differences and features of using Fragment in Android?

sobes.tech AI

Answer from AI

Fragment is a modular component of the user interface in Android that represents a part of an activity. Main features and differences:

  • Lifecycle: Fragments have their own lifecycle, closely related to the activity they are in.
  • UI reuse: They allow creating reusable UI components that can be used in different activities or adapted to different screen sizes.
  • Dynamic UI management: Fragments can be added, replaced, or removed dynamically during app execution.
  • Communication with activity: Fragments can interact with the parent activity and other fragments via interfaces or ViewModel.

Example of using a Fragment in an activity:

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

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

Fragments are useful for adapting interfaces to different devices (e.g., tablets and phones) and organizing complex UI from independent parts.

Can you describe the key differences and features of… - sobes.tech