0

Please help call another function outside the companion in Kotlin android main activity

class MainActivity{
    val name = "stackoverflow"

    companion object(){
        //call the both the name and showDialog from this main thread
    }
    
    fun showDialog(){
        Dialog.show()
    }
}
Dinesh
  • 1,410
  • 2
  • 16
  • 29
ekibet
  • 176
  • 2
  • 8

1 Answers1

0

I assume you want to showDialog in MainActivity. let's say other fragments or maybe from MainActivity itself.

Best approaches from this :

  1. Share viewModel and have livData that lets the observer in MainActivity know to launch Dialog.
  2. Call (requireActivity as? MainActivity).showDialog() from fragment hosted in MainActivity.
Balwinder SIngh
  • 1,831
  • 2
  • 24
  • 28
  • Please note: MainActivity does not have the viewModel since the design is based on single activity architecture. – ekibet Jan 30 '22 at 04:28
  • u don't need to have a dedicated viewModel for Mainactivity but what's stopping you to share ViewModel between your fragment and activity. – Balwinder SIngh Feb 01 '22 at 07:58