今天在掘金看到使用
Kotlin
高阶函数传递Intent
数据很简洁,觉着可以试试,并应用到项目中去,自己再加以理解,记录笔记,方便查阅。掘金原文章地址:https://mp.weixin.qq.com/s/0TuDlsfBtO7wP9TwI8CeJw
传统的Intent
数据传递我就不介绍了,只介绍Kotlin
实现方式:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21//目标 假设叫`KTestActivity4` 定义
object IntentOptions{
private const val MSG_KEY = "key for message"
var Intent.message: String?
get() = getStringExtra(MSG_KEY)
set(message) {
putExtra(MSG_KEY,message)
}
}
//跳转时
with(KTestActivity4.IntentOptions){
intent = Intent(this 5,KTestActivity4::class.java)
intent.message = "I am KTestActivity5"
startActivity(intent)
}
//使用
with(IntentOptions){
var message= intent.message
Toast.makeText(this 4,"显示信息:"+message,Toast.LENGTH_SHORT).show()
}
假设有多个数据传递:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23object IntentOptions{
private const val MSG_KEY = "key for message"
private const val MSG_ID = "ID for message"
var Intent.message: String?
get() = getStringExtra(MSG_KEY)
set(message) {
putExtra(MSG_KEY,message)
}
// 再多增加一条即可
var Intent.id: String?
get() = getStringExtra(MSG_ID)
set(id) {
putExtra(MSG_ID,id)
}
}
// 传递时
with(KTestActivity4.IntentOptions){
intent = Intent(this 5,KTestActivity4::class.java)
intent.message = "I am KTestActivity5"
intent.id = "I am id"
startActivity(intent)
}
还有另外一种传递方式:委托机制,不是特别明白。国外大神封装的github
地址:https://github.com/Takhion/android-extras-delegates