ActivityResultLauncher<Intent> launcherImportFileSelection = requireActivity().registerForActivityResult(...
如果上面的代码放在onCreate(Bundle savedInstanceState)中,则会抛出以下异常:
Exception: LifecycleOwner MyActivity@868498a is attempting to register while current state is RESUMED. LifecycleOwners must call register before they are STARTED.
如果它被放置在构造函数中或作为声明,requireActivity()会抛出以下异常:
java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
2021-04-17 15:15:41.948 27930-27930/net.biyee.onvifer E/AndroidRuntime: at androidx.fragment.app.Fragment.instantiate(Fragment.java:613)
... 42 more
Caused by: java.lang.IllegalStateException: Fragment MyFragment{fba6d22} (e0d1f006-996d-4051-9839-4575a92e33dd) not attached to an activity.
at androidx.fragment.app.Fragment.requireActivity(Fragment.java:928)
我在build.gradle中有以下内容:
implementation 'androidx.fragment:fragment:1.3.2'
有人能提供一个提示吗?
更新:
问题已经解决了。请看我与@CommmonsWare的交流。
2条答案
按热度按时间qxsslcnc1#
您需要在
onCreate()
方法之外设置一个寄存器调用,此外,您还需要将registerForActivityResult()
变量作为片段类的属性。(仅适用于Activity
,而不是Fragment
!)Kotlin注册调用示例:
}
JAVA注册调用示例:
本文档将帮助您理解和实践。干杯:)
pxq42qpu2#
如在单独的类中接收活动结果中所述,
Fragment类实现ActivityResultCaller接口,以允许您使用registerForActivityResult()API
因此,您可以像在Activity中一样使用它: