[英]How to call a method of a Fragment from another Fragment?
知道 TargetFragment 現在已棄用,如何從 DialogFragment 調用 Fragment 的方法?
在過去,我可以這樣做:
父片段
DialogFragment dialog = new DialogFragment();
dialog.setTargetFragment(this, 0);
dialog.show(this.getSupportFragmentManager(), "tag");
對話片段
((ParentFragment) this.getTargetFragment()).myMethod();
這不再可能,因為 TargetFragment 現在已棄用。
我讀到我可以使用setFragmentResultListener()來傳遞變量,但是如何從 DialogFragment 調用 ParentFragment.myMethod() 方法?
這是我找到的解決方案。
父片段
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();
}
});
}
對話片段
Bundle result = new Bundle();
result.putString("action", "myMethod");
this.getParentFragmentManager().setFragmentResult("result", result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.