registerForActivityResult应在fragment或activity创建之前调用
就是说,如果要为返回的结果注册监听器的话,不能在fragment或activity已经创建好了再调用。
可以放在字段中:
class CrimeFragment : Fragment() { ... private val aLauncher = registerForActivityResult(ActivityResultContracts.PickContact()) { uri: Uri? -> doWhenChooseSuspect(uri) } private val requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { isGranted: Boolean -> if (isGranted) { aLauncher.launch() } else { Toast.makeText( context, "we need the permission to get suspect", Toast.LENGTH_LONG ).show() } } ......
文档有这么一段话:This *must* be called unconditionally, as part of initialization path, typically as a field initializer of an Activity or Fragment.

浙公网安备 33010602011771号