Search code examples
androidkotlinonclicklistener

How to call a function from button click kotlin


I have two activities, LoginActivity and MainActivity. When I press a button in my LoginActivity I want to call a function in MainActivity.How can I achieve this?

  • MainActivity function*
    fun triggerRestart(context: Activity) {
        val intent = Intent(context, MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        context.startActivity(intent)
        if (context is Activity) {
            (context as Activity).finish()
        }
        Runtime.getRuntime().exit(0)
    }

Please give me a proper solution. Thanks


Solution

  • There are 3 ways to do it in Kotlin:

    1. Using Object - As it is a static function which doesn't access views or data of MainActivity, you can call it through an object of MainActivity as it need not be the running instance.

      So, you can call it as MainActivity().triggerRestart().

    2. Using Companion Object - You can also declare the function in Comapnion Object of MainActivity as

      Companion object {
          fun triggerRestart(context: Activity) {
              val intent = Intent(context, MainActivity::class.java)
              intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
              context.startActivity(intent)
              if (context is Activity) {
                  (context as Activity).finish()
              }
              Runtime.getRuntime().exit(0)
          }
      }
      

      And then can access it as MainActivity.triggerRestart().

    3. Getting instance from Companion Object - You can get an instance of the MainActivity and then, can access the function through it as:

      Companion object {
          val instance = MainActivity()
      
      }
      
      fun triggerRestart(context: Activity) {
          val intent = Intent(context, MainActivity::class.java)
          intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
          context.startActivity(intent)
          if (context is Activity) {
              (context as Activity).finish()
          }
          Runtime.getRuntime().exit(0)
      }
      

      and then can access it as MainActivity.instance.triggerRestart().

    Difference between first and second is that you don't have to unncessarily create an object of MainActivity in second way to access a static function.

    Difference between second and third is in third, you're accessing the function through an instance of activity passed by the activity itself, unnecessary for static values but important in case you want to access the views/values of running instance of the MainActivity.

    You can further improve the third way to ensure that it passes only the running instance and not new instance. For that, create a private temp var and intialize it as this(which means Activity) in init() of the class and pass it as the instance. This way, third will pass the running instance of the activity.