Android Replace Fragment

Kevin FOO
2 min readMar 19, 2021

--

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”.

fun AppCompatActivity.replaceFragment(fragment:Fragment){
val fragmentManager = supportFragmentManager
val transaction = fragmentManager.beginTransaction()
transaction.replace(R.id.host,fragment)
//transaction.addToBackStack(null)
transaction.commit()
}

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”.

button1?.setOnClickListener {
val
context = activity as AppCompatActivity
context.replaceFragment(TwoFragment())
}

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

< Back to all the stories I had written

--

--

Kevin FOO
Kevin FOO

Written by Kevin FOO

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