Search code examples
androidkotlinandroid-fragmentsnavigation

How to pop back to main menu activity in Kotlin


I have a main menu activity that the user can go into several different functions. When they click one, I move them to that activity and then open fragments. At any point, they can click Done to go back to the main menu, but right now it only goes back to the first fragment. Am I handling the activity > activity > fragments stack incorrectly?

Here's the main menu

   binding.putaway.setOnClickListener {
        val intent = Intent(this, PutAwayMainActivity::class.java)
        startActivity(intent)
    }
    binding.cyclecount.setOnClickListener {
        val intent = Intent(this, CycleCountMainActivity::class.java)
        startActivity(intent)
    }
    binding.transfer.setOnClickListener {
        val intent = Intent(this, TransferMainActivity::class.java)
        startActivity(intent)
    }
    binding.itemlookup.setOnClickListener {
        val intent = Intent(this, ItemLookupMainActivity::class.java)
        startActivity(intent)
    }
    binding.newreceipt.setOnClickListener {
        val intent = Intent(this, NewReceiptMainActivity::class.java)
        startActivity(intent)
    }
    binding.additem.setOnClickListener {
        val intent = Intent(this, NewReceiptAddItemMainActivity::class.java)
        startActivity(intent)
    }

Here's my new receipt main activity

class NewReceiptMainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_new_receipt_main)

        val fragment = NewReceiptSelectProgram()
        val fram = supportFragmentManager.beginTransaction()
        fram.replace(R.id.nav_newreceipt_fragment,fragment)
        fram.commit()
    }
}

Here's how I'm attempting to pop back (this only goes back to NewReceiptSelectProgram instead of MainMenu)

    private fun donePressed() {
        parentFragmentManager.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
    }

Solution

  • I think this should help:

        private fun donePressed() {
            requireActivity().finish()
        }