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:
- Create a class that inherits from
Fragment. - Override the
onCreateViewmethod, where you programmatically create and return the root View. - 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.