用Intent傳輸數(shù)據(jù)是安卓常用技術之一,通常的方法是聲名一堆鍵名(key_name)凯沪,把數(shù)據(jù)存儲到Intent中第焰,然后在其它地方根據(jù)鍵名和類別讀取。
示例如下:
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’什么的烘跺。取無意義鍵名湘纵,容易出現(xiàn)用錯名或類型錯誤的問題,怎么破滤淳?用XIntent傳輸數(shù)據(jù)梧喷,超簡潔!
啟動Activity
//直接啟動新頁面脖咐,可以把數(shù)據(jù)跟在后面
XIntent.startActivity(this, MainActivity::class, name, pwd, newUser)
//startActivityForResult方式啟動
val intent = XIntent(this, MainActivity::class, name, pwd, newUser)
startActivityForResult(intent, 1)
//讀取上個頁面?zhèn)鬟^來的數(shù)據(jù)
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()
}
方法說明
//支持三種類型參數(shù)
XIntent.with(Activity | Intent? | Bundle): IntentWrapper
IntentWrapper{
//請確保傳入?yún)?shù)都能強制轉換為serializable铺敌,支持 List<String>,不支持 List<Activity>
fun putSerializableExtra(vararg serializable: Any?)
fun getSerializableExtra(): Array<Serializable?>?
//根據(jù)數(shù)據(jù)類型讀取屁擅,注:不支持 List 類型(能讀到數(shù)據(jù)适刀,但List的泛型無法讀到)
inline fun <reified T : Serializable> readExtra(defaultValue: T? = null): T?
//根據(jù) Index 讀取類型重復的數(shù)據(jù)
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
最后
如果本文幫助到了你,也幫我點個贊吧煤蹭!
如果你愿意笔喉,還可以贊賞一杯咖啡或一瓶水,非常感覺你的慷慨硝皂!