registerForActivityResult 封装基类
程序员文章站
2022-06-22 18:49:10
封装完后的用法: startForActivityResult(CActivity::class.java){resultCode, data -> if(resultCode == Activity.RESULT_OK){ val data2 = data.getStringExtra("data2") } }使用startActivityF...
封装完后的用法:
startForActivityResult(CActivity::class.java){resultCode, data ->
if(resultCode == Activity.RESULT_OK){
val data2 = data.getStringExtra("data2")
}
}
使用startActivityForResult的时候,由于有requestCode,我们可以知道data和resultCode从哪个activity里回调回来,但使用registerForActivityResult的时候……
先看看registerForActivityResult的基本用法吧,两个按钮,跳转方式分别为 AAct-->BAct-->AAct AAct-->CAct-->AAct
class AActivity : AppCompatActivity() {
private val startForActivityResult1 = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
it.resultCode
it.data
}
private val startForActivityResult2 = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
btnJump1.setOnClickListener {
startForActivityResult1.launch(Intent(this,BActivity::class.java))
}
btnJump2.setOnClickListener {
startForActivityResult2.launch(Intent(this,CActivity::class.java))
}
}
}
由于回调数据没有可以识别出是从哪个activity回调,register后回调无法复用,本身又是个final方法,无法重写,所以跳转到每个activity都需要写一次register,使用方法非常的繁琐
这样看似无解,但如果仔细看源码,可以发现回调顺序遵循的是FILO,这就好办了,封装一下:
open class BaseActivity : AppCompatActivity() {
private val resultCallBacks: Deque<ResultCallBack> = ArrayDeque()
private val activityForResult =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
resultCallBacks.pop()?.let {
it(result.resultCode, result.data?: Intent())
}
}
@JvmOverloads
protected fun startForActivityResult(
cls: Class<*>,
block: Intent.() -> Unit = {},
callBack: ResultCallBack
) {
resultCallBacks.push(callBack)
activityForResult.launch(Intent(this, cls).apply(block))
}
}
使用:
startForActivityResult(CActivity::class.java, {
putExtra("data1", "data")
}) { resultCode, data ->
}
本文地址:https://blog.csdn.net/jingzz1/article/details/110236804