Home > front end >  Remove Fragment from MainActivity
Remove Fragment from MainActivity

Time:09-29

I was able to make a fragment as below

supportFragmentManager.beginTransaction().replace(R.id.fragment2, ConsumeFragment.newInstance(consumerTitle)).commit()

and my ConsumeFragment Class

class ConsumeFragment : Fragment()
   companion object {
        const val titleKey = "consumeTitle"
        fun newInstance(title: String): ConsumeFragment {
            val frag = ConsumeFragment()
            val bundle = Bundle()
            bundle.putString(titleKey, title)
            frag.arguments = bundle
            return frag
        }

Now I am trying to remove the fragment by clicking the button as below

binding.killConsumeBut.setOnClickListener{
Log.d("XXX", "click KillConsumerButton")
supportFragmentManager.beginTransaction().remove(ConsumeFragment()).commit()}

However, it doesn't remove the fragment. What should I do instead?

CodePudding user response:

Quoting the documentation for remove():

Remove an existing fragment

(emphasis added)

You are creating a new fragment instance via ConsumeFragment(), then are trying to remove it. That is not going to work.

Instead, hold onto the ConsumeFragment instance that you added previously, and use remove() with it. Or, find the fragment in your FragmentManager (e.g., via findFragmentById()), then call remove() with it.

  • Related