Sobes.tech
Junior — Middle

Is it possible and how to implement a Fragment using code?

sobes.tech AI

Answer from AI

Yes, a Fragment in Android can be created and managed entirely programmatically, without using XML layout. To do this:

  1. Create a class that inherits from Fragment.
  2. Override the onCreateView method, where you programmatically create and return the root View.
  3. Add the Fragment to an Activity via FragmentManager using code.

Example of creating a simple Fragment with a programmatically created View:

class MyFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        val textView = TextView(requireContext())
        textView.text = "Programmatically created Fragment"
        textView.gravity = Gravity.CENTER
        textView.textSize = 20f
        return textView
    }
}

Adding a Fragment to an Activity programmatically:

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

Thus, the entire UI and fragment logic can be created and managed through code without XML.