如何将 registerForActivityResult 与 androidx.fragment.app.Fragment 一起使用?

Hon*_*ong 10 android androidx

 ActivityResultLauncher<Intent> launcherImportFileSelection = requireActivity().registerForActivityResult(...
Run Code Online (Sandbox Code Playgroud)

如果上面的代码放在onCreate(Bundle savingInstanceState)中,会抛出以下异常:

Exception: LifecycleOwner MyActivity@868498a is attempting to register while current state is RESUMED. LifecycleOwners must call register before they are STARTED.
Run Code Online (Sandbox Code Playgroud)

如果将其放置在构造函数中或作为声明,则 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)
Run Code Online (Sandbox Code Playgroud)

我在 build.gradle 中有以下内容:

implementation 'androidx.fragment:fragment:1.3.2'
Run Code Online (Sandbox Code Playgroud)

有人可以提供这方面的建议吗?

更新:

问题已经解决了。请参阅我与@CommmonsWare 的交流

DEX*_*7RA 4

您需要在onCreate()方法外部设置一个寄存器调用,此外您还需要将registerForActivityResult()变量作为片段类的属性。(仅适用于Activity而不是Fragment!)

KOTLIN的注册调用示例:

val getContent = registerForActivityResult(GetContent()) { uri: Uri? ->
// Handle the returned Uri
Run Code Online (Sandbox Code Playgroud)

}

JAVA的注册调用示例:

// GetContent creates an ActivityResultLauncher<String> to allow you to pass
// in the mime type you'd like to allow the user to select
ActivityResultLauncher<String> mGetContent = registerForActivityResult(new GetContent(),
    new ActivityResultCallback<Uri>() {
        @Override
        public void onActivityResult(Uri uri) {
            // Handle the returned Uri
        }
});
Run Code Online (Sandbox Code Playgroud)

文档将帮助您理解和实践。干杯:)