[英]How to call a method of a Fragment from another Fragment?
How can I call a method of a Fragment from a DialogFragment, knowing that TargetFragment is now deprecated ?知道 TargetFragment 现在已弃用,如何从 DialogFragment 调用 Fragment 的方法?
In the past, I could do it this way:在过去,我可以这样做:
ParentFragment父片段
DialogFragment dialog = new DialogFragment();
dialog.setTargetFragment(this, 0);
dialog.show(this.getSupportFragmentManager(), "tag");
DialogFragment对话片段
((ParentFragment) this.getTargetFragment()).myMethod();
This is no longer possible, because TargetFragment is now deprecated.这不再可能,因为 TargetFragment 现在已弃用。
I read that I can use setFragmentResultListener() to pass variables, but how can I call the ParentFragment.myMethod() method from the DialogFragment?我读到我可以使用setFragmentResultListener()来传递变量,但是如何从 DialogFragment 调用 ParentFragment.myMethod() 方法?
Here is the solution I found.这是我找到的解决方案。
ParentFragment父片段
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getParentFragmentManager().setFragmentResultListener("result", this, new FragmentResultListener() {
public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle bundle) {
String action = bundle.getString("action");
if (action != null)
if (action.equals("myMethod"))
ParentFragment.this.myMethod();
}
});
}
DialogFragment对话片段
Bundle result = new Bundle();
result.putString("action", "myMethod");
this.getParentFragmentManager().setFragmentResult("result", result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.