Android Replace Fragment

Been googling several sites on how to navigate/traverse between fragments in Android. It is not easy because it is mostly in Java and they are so old and deprecated. Finally after piecing together the information from several sites, I managed to get it working.

I better document it down for my own use in future. Don’t want to go through the tiring process of googling again.

At MainActivity.kt , add the function “replaceFragment”.

The id of my activity_main.xml constraint layout is “host”. By default it is empty when you create a new project.

To generate onViewCreated. Right click “Generate…” > “Override Methods…”. Then search for “onViewCreated”.

In fragment_one.xml , setOnClickListener for button1 so that it will navigate to fragment_two.xml

< Back to all the stories I had written

A software engineer, a rock climbing, diving & inline skating enthusiast, a husband, a father.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store