看看这个"startActivityForResult()"代码,这个函数已被弃用。如何在片段中更改此代码?



看这个startActivityForResult()代码,这个函数已经弃用了。如何在Fragment中更改此代码?

Call Activity是什么意思?startActivityForResult(Intent, int) from fragment's contains Activity."?

请给我指路…

private const val REQUEST_PHOTO = 2
class ExampleFragment:Fragment(), DatePickerFragment.Callbacks {
private lateinit var photoUri : Uri
override fun onStart() {
super.onStart()
...
photoButton.apply {
val packageManager : PackageManager = requireActivity().packageManager
val captureImage = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
val resolvedActivity : ResolveInfo? =
packageManager.resolveActivity(captureImage,
PackageManager.MATCH_DEFAULT_ONLY)
if (resolvedActivity == null) {
isEnabled = false
}
setOnClickListener {
captureImage.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
val cameraActivities : List<ResolveInfo> =
packageManager.queryIntentActivities(captureImage, PackageManager.MATCH_DEFAULT_ONLY)
for (cameraActivity in cameraActivities) {
requireActivity().grantUriPermission(
cameraActivity.activityInfo.packageName,photoUri,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION
)
}
startActivityForResult(captureImage, REQUEST_PHOTO)  // <<<< Deprecated 
}
}
}

首先创建类型为ActivityResultLauncher的变量captureImageLauncher

你必须注册一个结果回调:(这是以前使用的onActivityResult方法的替代方案)像这样。所以你可以移动onActivityResult下的所有代码在这个回调

private val captureImageLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
result: ActivityResult ->

// Here You handle the result that the activity sent back
// You can use methods like result.resultCode or result.data to retrieve information
}

这将创建一个ActivityResultLauncher,您稍后将使用它来代替startActivityForResult,如下所示:(代替startActivityForResult方法。您也不需要显式的请求代码,因为这会使事情变得不必要的复杂)

captureImageLauncher.launch(captureImage) // captureImage is the intent that You've created

更多信息请点击此处。

相关内容

  • 没有找到相关文章

最新更新