我想检测是从Activity还是Fragment打开DialogFragment。因为调用的Activity或Fragment将为侦听器附加一个接口。
如果“活动”用于显示对话框: (我将在DialogFragment中编写)
listener = (MyListener) getActivity();
否则,如果Fragment正在调用对话框:
listener = (MyListener) getParentFragment;
所以,我需要检测谁在调用对话框片段!
答案 0 :(得分:1)
void showDialog() {
DialogFragment newFragment = new MyAlertDialogFragment();
newFragment.setFromActivity(true); pass here.
newFragment.show(getFragmentManager(), "dialog");
}
在您的DialogFragment
public static class MyAlertDialogFragment extends DialogFragment {
boolean isFromActivity;
public void setFromActivity(boolean isFromActivity){
this.isFromActivity = isFromActivity;
}
}
您应该使用设置器来编写通用代码,以便将来可以只通过侦听器。
DialogFragment newFragment = new MyAlertDialogFragment();
newFragment.setListener(this); // or use anonymous deriving like new Listener()...
答案 1 :(得分:1)
我对问题使用以下样式,将其发布为答案,因为这可能会对某人有所帮助。
public MyDialog extends DialogFragment{
private MyListener listener;
public static MyDialog newInstance(MyListener callback){
MyDialog dialog = new MyDialog();
dialog.listener = callback;
return dialog;
}
//rest of the Dialog code such as onCreate() etc..
}
并通过“任何活动”或“片段”进行呼叫
活动
public MyActivity extends AppCompatActivity implements MyListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
MyDialog dialog = MyDialog.newInstance(this);
dialog.show(getSupportFragmentManager, "TAG");
}
}
片段
public MyFragment extends Fragment implements MyListener{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.my_frag_layout, container, false);
MyDialog dialog = MyDialog.newInstance(this);
dialog.show(getChildFragmentManager, "TAG");
return view;
}
}
如果可能发生错误或条件崩溃,请发表评论。谢谢!