如何在androidx.fragment.app.Fragment中使用registerForActivityResult?

u5i3ibmn  于 2023-04-18  发布在  Android
关注(0)|答案(2)|浏览(404)
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的交流。

qxsslcnc

qxsslcnc1#

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

Kotlin注册调用示例:

val getContent = registerForActivityResult(GetContent()) { uri: Uri? ->
// Handle the returned Uri

}

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
        }
});

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

pxq42qpu

pxq42qpu2#

如在单独的类中接收活动结果中所述,
Fragment类实现ActivityResultCaller接口,以允许您使用registerForActivityResult()API
因此,您可以像在Activity中一样使用它:

public class YourFragment extends Fragment {

    private final ActivityResultLauncher<input_type> mActivityResultLauncher = 
            registerForActivityResult(<your_contract>, <your_callback>);

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // just don't register here
        ...
    }

    // call this when needed (e.g. user presses a button)
    private void launchActivityForResult() {
        mActivityResultLauncher.launch(<input>);
    }

}

相关问题