I have two fragments, named them "Red" and "Blue" and three buttons. The first one adds "Red" fragment and changes the background to red color, the second one adds "Blue" fragment and changes the background to blue color and the third one has to remove the current fragment and change the color to the previous fragment's color.
The problem is that when I click the remove button I see a toast that the fragment is removed but the layout doesn't change to the color of the previous fragment.
var fragment1 = FirstFragment()
var fragment2 = SecondFragment()
lateinit var binding: ActivityMainBinding
var counter: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.redBtn.setOnClickListener {
supportFragmentManager
.beginTransaction()
.add(R.id.placeHolder, fragment1)
.addToBackStack("Red")
.commit()
counter++
binding.count.text = "$counter"
}
binding.blueBtn.setOnClickListener {
supportFragmentManager
.beginTransaction()
.replace(R.id.placeHolder, fragment2)
.addToBackStack("Blue")
.commit()
counter++
binding.count.text = "$counter"
}
binding.removeBtn.setOnClickListener {
val fragmentInstance = supportFragmentManager.findFragmentById(R.id.placeHolder)
if(fragmentInstance is FirstFragment){
supportFragmentManager.beginTransaction()
.remove(FirstFragment())
.commit()
Toast.makeText(this, "Removed Red Fragment", Toast.LENGTH_SHORT).show()
} else {
supportFragmentManager.beginTransaction()
.remove(SecondFragment())
.commit()
Toast.makeText(this, "Removed Blue Fragment", Toast.LENGTH_SHORT).show()
}
counter--
binding.count.text = "$counter"
}
}
}
It will not remove directly
Then when you add or remove fragment from fragment manager use the same fragment object
Like you created fragment1 and fragment2