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'
有人可以提供这方面的提示吗?
更新:
问题已解决。请参阅我与@CommonsWare的交流。
您需要在
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
}
});
此文档将帮助您理解和实践。干杯:)
如Receive an activity result in a separate class,
片段类实现 ActivityResultCaller 接口让 你使用 registerForActivityResult() APIs
所以你可以像在活动中一样使用它:
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>);
}
}