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.

posted @ 2021-06-03 11:32  ou尼酱~~~  阅读(1324)  评论(0)    收藏  举报