在fragment中使用ActivityResultLauncher需要用到registerForActivityResult方法,并且在onActivityResult方法中调用launcher的回调方法。但是在fragment中,无法重写onActivityResult方法,因此无法处理结果。
为了解决这个问题,可以使用在fragment中获取的Activity对象来创建ActivityResultLauncher,在onActivityResult方法中通过调用Activity的getActivityResultManager方法来处理结果。
示例:
public class MyFragment extends Fragment {
private ActivityResultLauncher
@Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_my, container, false); Button button = view.findViewById(R.id.button); myLauncher = registerForActivityResult(new ActivityResultContracts.GetContent(), uri -> { //处理结果 });
button.setOnClickListener(v -> myLauncher.launch("image/*"));
return view;
}
@Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); Activity activity = getActivity(); if (activity != null) { activity.getResultManager().onActivityResult(requestCode, resultCode, data); } } }