startActivityForResult弃用! Activity Results API
背景 : startActivityForResult弃用,主要是由于不够解耦,本文将介绍 : Activity Results API
一、自定义ActivityResultContract
class MyActivityResultContract: ActivityResultContract<String, String>(){
override fun createIntent(context: Context, input: String?): Intent {
return Intent(context, SecondActivity::class.java).apply {
putExtra("pass",input)
}
}
override fun parseResult(resultCode: Int, intent: Intent?): String? {
val data = intent?.getStringExtra("back")
return if (resultCode == Activity.RESULT_OK && data != null) data
else null
}
}
二、注册协议,获取启动器-ActivityResultLauncher
private val myActivityLauncher = registerForActivityResult(MyActivityResultContract()) {
Toast.makeText(this, it, Toast.LENGTH_LONG).show()
Log.e("youdianxiaoshuai", "it--------> :$it")
}
binding.firstButton.setOnClickListener {
myActivityLauncher.launch("KD")
}
三、第二个Activity setResult
class SecondActivity :AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
initView()
val extra = intent.getStringExtra("pass")
Log.e("youdianxiaoshuai", "extra ----->$extra")
}
override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
super.onCreate(savedInstanceState, persistentState)
}
private fun initView() {
binding.button.setOnClickListener {
val intent = Intent().apply {
putExtra("back","回传数据")
}
setResult(Activity.RESULT_OK,intent)
}
}
private val binding:SecondActivityBinding by lazy {
SecondActivityBinding.inflate(layoutInflater)
}
}