参考:https://blog.youkuaiyun.com/NakajimaFN/article/details/126542605
package com.example.kotlingradletemplatefirst
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button = findViewById<Button>(R.id.button00)
/**
* 1、Android中旧版本的startActivityForResult替代方法为【registerForActivityResult】
* 1、这个registerForActivityResult方法要写在Activity的onCreate方法里(在Activity创建的时候就要创建出来,不能等到使用的时候再创建,不然会报错LifecycleOwner com.xx.MainActivity@28b4e79 is attempting to register while current state is RESUMED. LifecycleOwners must call register before they are STARTED.)。
*/
val intentActivityResultLauncher = registerForActivityResult<Intent, ActivityResult>(
StartActivityForResult()
) { result: ActivityResult ->
if (result.resultCode == RESULT_OK) {
println("data=${result.data?.getStringExtra("goto")}")
}
}
button.setOnClickListener {
val intent = Intent(this, GoToActivity::class.java)
intent.putExtra("name", "ok")
intentActivityResultLauncher.launch(intent)
}
}
}
package com.example.kotlingradletemplatefirst
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
class GoToActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.my_test)
val button = findViewById<Button>(R.id.button01)
button.text = "update"
button.setOnClickListener {
/**
* 1、子activity返回数据进入主activity
*/
val intentResult = Intent(this, MainActivity::class.java)
intentResult.putExtra("goto", "goto")
setResult(Activity.RESULT_OK, intentResult)
finish()
}
}
}