Challenge 1: A Basic Fragment — Solution
// fragment_welcome.xml
// WelcomeFragment.kt
class WelcomeFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
return inflater.inflate(R.layout.fragment_welcome, container, false)
}
}
// activity_main.xml
// MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.replace(R.id.fragmentContainer, WelcomeFragment())
.commit()
}
}
}
Notes:
- WelcomeFragment.onCreateView inflates fragment_welcome.xml and returns
it — the returned View is what the FragmentManager places into
fragmentContainer.
- The "if (savedInstanceState == null)" check prevents a duplicate
WelcomeFragment from being added every time the Activity recreates
(e.g. on rotation) — the FragmentManager already automatically
restores whatever Fragment was showing before recreation.
- replace(R.id.fragmentContainer, WelcomeFragment()) is used even for
this very first load, since it's the standard call whether adding a
Fragment for the first time or swapping one out later (Challenge 2).