androidkotlinkotlin-android-extensionskotlin-extension

Kotlin extension function start activity with Intent extras


I am trying to write a kotlin extension function for Context which will start a new activity in android with given class name and list of intent extras. I am able to successfully start activity without any extras but I am facing problem with them.

fun <T> Context.openActivity(it: Class<T>, pairs: List<Pair<String, Any>>) {
  var intent = Intent()
  pairs.forEach {
     intent.putExtra(it.first, it.second)
  }
  startActivity(intent)
}

Main issue here is -> intent.putExtra() doesn't except second param as Any


Solution

  • Instead of using a list of pairs, consider using a Bundle. Then you can add it with putExtras(Bundle).

    If you want to go one step ahead, you could add a lambda extension to configure the extras:

    fun <T> Context.openActivity(it: Class<T>, extras: Bundle.() -> Unit = {}) {
      val intent = Intent(this, it)
      intent.putExtras(Bundle().apply(extras))
      startActivity(intent)
    }
    

    Then you can call it as:

    openActivity(MyActivity::class.java) {
      putString("string.key", "string.value")
      putInt("string.key", 43)
      ...
    }