如何在startActivityForResult()中传递数据并在onActivityResult()中取回数据?

时间:2019-06-08 02:37:49

标签: android kotlin

这是我的startActivityForResult()

val initialPosition = frame.tag as Int
val currentPosition = constraint.indexOfChild(frame)
Log.d(TAG, "initial position: $initialPosition") // prints initial position: 2
Log.d(TAG, "current position: $currentPosition") // prints current position: 2
val galleryIntent = Intent().apply {
  type = "image/*"
  action = Intent.ACTION_PICK
  putExtra("initialPosition", initialPosition)
  putExtra("currentPosition", currentPosition)
  setResult(5)
}
startActivityForResult(Intent.createChooser(galleryIntent, "Pick image"), PICK_IMAGE_REQUEST_CODE)

但是,我无法在此处检索数据:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    if (resultCode == Activity.RESULT_OK){
        Log.d(TAG, "ResultCode: $resultCode SUCCESS") // prints -1 SUCCESS
    }
    when (requestCode){
        PICK_IMAGE_REQUEST_CODE -> {
            Log.d(TAG, "${data?.getIntExtra("initialPosition", 0)}") // prints 0
            Log.d(TAG, "${data?.extras?.getInt("initialPosition")}") // prints 0
            Log.d(TAG, "${data?.extras?.getInt("currentPosition")}") // prints 0
        }
    }
    super.onActivityResult(requestCode, resultCode, data)
}

知道为什么吗?

1 个答案:

答案 0 :(得分:0)

setResult()不会设置galleryIntent的结果代码。可以设定结果的是您在Intent.ACTION_PICK期间选择的活动。

假设您选择了系统映像选择器。如果选择图像,它将返回RESULT_OK(为-1),如果您按下图像,则返回RESULT_CANCELED(为0)。

请注意,如果您使用的是resultCode,那么您将无法更改Implicit Intent返回的其他活动。