很简单的问题:是否可以为第二个Pair参数(字符串,Int,Bundle等)找到通用的Intent额外类型?
inline fun <reified T : Activity> Context.startActivity(vararg params: Pair<String, ?>) {
val intent = Intent(this, T::class.java)
params.forEach { intent.putExtra(it.first, it.second) }
startActivity(intent)
}
谢谢
最佳答案
我相信当前的语言功能和Android API无法实现这一点。
如果您深入了解Anko的源,您会发现它们最终也采用了琐碎且有点丑陋的解决方案。 (对于您应该使用的更高级别的公共(public)功能,它们使用vararg params: Pair<String, Any?>
,然后委托(delegate)给以下对象。)
@JvmStatic
private fun fillIntentArguments(intent: Intent, params: Array<out Pair<String, Any?>>) {
params.forEach {
val value = it.second
when (value) {
null -> intent.putExtra(it.first, null as Serializable?)
is Int -> intent.putExtra(it.first, value)
is Long -> intent.putExtra(it.first, value)
is CharSequence -> intent.putExtra(it.first, value)
is String -> intent.putExtra(it.first, value)
is Float -> intent.putExtra(it.first, value)
is Double -> intent.putExtra(it.first, value)
is Char -> intent.putExtra(it.first, value)
is Short -> intent.putExtra(it.first, value)
is Boolean -> intent.putExtra(it.first, value)
is Serializable -> intent.putExtra(it.first, value)
is Bundle -> intent.putExtra(it.first, value)
is Parcelable -> intent.putExtra(it.first, value)
is Array<*> -> when {
value.isArrayOf<CharSequence>() -> intent.putExtra(it.first, value)
value.isArrayOf<String>() -> intent.putExtra(it.first, value)
value.isArrayOf<Parcelable>() -> intent.putExtra(it.first, value)
else -> throw AnkoException("Intent extra ${it.first} has wrong type ${value.javaClass.name}")
}
is IntArray -> intent.putExtra(it.first, value)
is LongArray -> intent.putExtra(it.first, value)
is FloatArray -> intent.putExtra(it.first, value)
is DoubleArray -> intent.putExtra(it.first, value)
is CharArray -> intent.putExtra(it.first, value)
is ShortArray -> intent.putExtra(it.first, value)
is BooleanArray -> intent.putExtra(it.first, value)
else -> throw AnkoException("Intent extra ${it.first} has wrong type ${value.javaClass.name}")
}
return@forEach
}
}
您可以在这里找到文件:https://github.com/Kotlin/anko/blob/683115f93ca6b0ed36ab36f3814dbc0da0abe7d3/anko/library/static/common/src/Internals.kt#L143