startActivityForResult alternative

startActivityForResult alternative

The startActivityForResult() method is used to return data to the previous Activity.

But this method has been deprecated for a long time, and now Google uses the registerForActivityResult() method to implement this function.

registerForActivityResult() implementation

Use registerForActivityResult() to implement SecondActivity to return data to FirstActivity

FirstActivity code

class FirstActivity : AppCompatActivity() {
    
    

    private val requestDataLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
    
     result ->
            if (result.resultCode == RESULT_OK) {
    
    
                val data = result.data?.getStringExtra("data")
                Log.d("FirstActivity", "data =${
      
      data}")
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
    
    
        super.onCreate(savedInstanceState)
        val binding = FirstLayoutBinding.inflate(layoutInflater)
        setContentView(binding.root)
        val button = binding.button1
        button.setOnClickListener {
    
    
            val intent = Intent(this, SecondActivity::class.java) 
            requestDataLauncher.launch(intent) //调用 launch 方法,该方法接收 输入类型 I
        }
    }
}

SecondActivity code

class SecondActivity : AppCompatActivity() {
    
    
    override fun onCreate(savedInstanceState: Bundle?) {
    
    
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)
        val binding = ActivitySecondBinding.inflate(layoutInflater)
        setContentView(binding.root)
        val button2 = binding.button2
        button2.setOnClickListener() {
    
    
            val intent = Intent()
          	intent.putExtra("data","register")
            setResult(RESULT_OK, intent)
            finish()
        }
    }
}

registerForActivityResult() method analysis

The registerForActivityResult() method receives two parameters.

  • The first parameter is a Contract type.

    Contract is used to specify that when an Activity is invoked, it uses I-type input and produces O-type output.

  • The second parameter is the callback. That is, when there is a return value, the code that processes the returned result. Implemented with lambda expressions

In the requirement of implementing an Activity to pass data to the next Activity

The first parameter can be passed to ActivityResultContracts.StartActivityForResult()

The input type I of this object is Intent, and the output type O is ActivityResult

The output type O is received in the parameter list in the callback function, so the corresponding operation can be performed on this output type O

Guess you like

Origin blog.csdn.net/jiaweilovemingming/article/details/124612035