android - Kotlin 扩展功能使用 Intent 附加功能启动 Activity

标签 android kotlin kotlin-android-extensions kotlin-extension

我正在尝试为 Context 编写一个 kotlin 扩展函数,它将在具有给定类名和 Intent 附加列表的 android 中启动一个新 Activity 。我能够在没有任何额外内容的情况下成功开始 Activity ,但我遇到了问题。

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

最佳答案

考虑使用 Bundle,而不是使用对列表.然后你可以用 putExtras(Bundle) 添加它.

如果您想提前一步,您可以添加一个 lambda 扩展来配置附加功能:

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

然后您可以将其称为:
openActivity(MyActivity::class.java) {
  putString("string.key", "string.value")
  putInt("string.key", 43)
  ...
}

关于android - Kotlin 扩展功能使用 Intent 附加功能启动 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53803667/

相关文章:

android - 多段线从起点和终点连接起来 |谷歌地图|安卓

Kotlin 协程 GlobalScope.launch 与 runBlocking

android - 由于android studio中缺少com.android.application插件,我的应用无法构建?

android - 我在哪里可以找到 android activity.xml 文件中命名空间的来源

android - Google Play Install Referrer API 与 INSTALL_REFERRER 广播

Android Firebase OrderByChild limitToLast 不工作

android - ListActivity的onListItemClick不起作用

arrays - 如何在 Kotlin 中定义 funs(函数)数组?

java - 如何更改 Kotlin 中 RecyclerView 中每个 Even 值元素的颜色?

Android库无法编译kotlin