用Intent传输数据是安卓常用技术之一,通常的方法是声名一堆键名(key_name),把数据存储到Intent中,然后在其它地方根据键名和类别读取。
示例如下:
val KEY_USER_NAME = "key_user_name"
val KEY_USER_PWD = "key_user_pwd"
val KEY_USER_NEW = "key_user_new"
val intent = Intent()
intent.putExtra(KEY_USER_NAME, "name")
intent.putExtra(KEY_USER_PWD, 123)
intent.putExtra(KEY_USER_NEW, true)
val name = intent.getStringExtra(KEY_USER_NAME)
val pwd = intent.getIntExtra(KEY_USER_PWD, -1)
val newUser = intent.getBooleanExtra(KEY_USER_NEW, false)
虽然取键名很简单,但如果取太多的话,就不知道取什么好了,到最后可能干脆直接用‘KEY_1’什么的。取无意义键名,容易出现用错名或类型错误的问题,怎么破?用XIntent传输数据,超简洁!
启动Activity
//直接启动新页面,可以把数据跟在后面
XIntent.startActivity(this, MainActivity::class, name, pwd, newUser)
//startActivityForResult方式启动
val intent = XIntent(this, MainActivity::class, name, pwd, newUser)
startActivityForResult(intent, 1)
//读取上个页面传过来的数据
XIntent.with(this).apply {
val name: String = readExtra()!!
val pwd: Int = readExtra()!!
val newUser: Boolean = readExtra()!!
}
SaveInstanceState
override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle?) {
super.onSaveInstanceState(outState, outPersistentState)
val saveTime = System.currentTimeMillis()
val user = "userName"
val pwd = 123
val newUser = true
XIntent.with(outState).putSerializableExtra(saveTime, user, pwd, newUser)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle, persistentState: PersistableBundle?) {
super.onRestoreInstanceState(savedInstanceState, persistentState)
XIntent.with(savedInstanceState).apply {
val saveTime: Long? = readExtra()
val user: String? = readExtra()
val pwd: Int? = readExtra()
val newUser: Boolean? = readExtra()
}
}
ActivityResult
//setResult
XIntent.with().apply {
val backTime = System.currentTimeMillis()
putSerializableExtra(backTime)
setResult(RESULT_OK, this)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val backTime: Long? = XIntent.with(data).readExtra()
}
方法说明
//支持三种类型参数
XIntent.with(Activity | Intent? | Bundle): IntentWrapper
IntentWrapper{
//请确保传入参数都能强制转换为serializable,支持 List<String>,不支持 List<Activity>
fun putSerializableExtra(vararg serializable: Any?)
fun getSerializableExtra(): Array<Serializable?>?
//根据数据类型读取,注:不支持 List 类型(能读到数据,但List的泛型无法读到)
inline fun <reified T : Serializable> readExtra(defaultValue: T? = null): T?
//根据 Index 读取类型重复的数据
inline fun <reified T : Serializable> readExtra(index: Int, defaultValue: T? = null): T?
inline fun <reified T : Serializable> readExtraList(): List<T>
}
Gradle dependency
allprojects {
repositories {
mavenLocal()
maven { url 'https://jitpack.io' }//add to project build.gradle
}
}
compile 'com.github.DonaldDu:XIntent:x.x.x'//add to module build.gradle
最后
如果本文帮助到了你,也帮我点个赞吧!
如果你愿意,还可以赞赏一杯咖啡或一瓶水,非常感觉你的慷慨!