[英]DialogFragment opened from Activity or Fragment?
I want to detect whether the DialogFragment is opened from an Activity or Fragment. 我想检测是从Activity还是Fragment打开DialogFragment。 Because the calling Activity or Fragment will have an Interface attached for a listener.
因为调用的Activity或Fragment将为侦听器附加一个接口。
if Activity is used to show the dialog: (inside DialogFragment I will write) 如果使用Activity显示对话框:(我将在DialogFragment中编写)
listener = (MyListener) getActivity();
else if Fragment is calling the dialog: 否则,如果Fragment正在调用对话框:
listener = (MyListener) getParentFragment;
So, I need to detect who is calling the dialog fragment! 因此,我需要检测谁在调用对话框片段!
void showDialog() {
DialogFragment newFragment = new MyAlertDialogFragment();
newFragment.setFromActivity(true); pass here.
newFragment.show(getFragmentManager(), "dialog");
}
In your DialogFragment
在您的
DialogFragment
public static class MyAlertDialogFragment extends DialogFragment {
boolean isFromActivity;
public void setFromActivity(boolean isFromActivity){
this.isFromActivity = isFromActivity;
}
}
You should do common code by using setters, so that in future you can just pass listener. 您应该通过使用setter来执行通用代码,以便将来可以只通过侦听器。
DialogFragment newFragment = new MyAlertDialogFragment();
newFragment.setListener(this); // or use anonymous deriving like new Listener()...
I am using the below style for my question, posting as an answer because it might help someone. 我对问题使用以下样式,将其发布为答案,因为这可能会对某人有所帮助。
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..
}
And calling from Any Activity or Fragment 并从任何活动或片段中调用
ACTIVITY 活动
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");
}
}
FRAGMENT 分段
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;
}
}
Please comment if there is any possiblity of error or conditions where it can crash. 如果有任何错误或可能导致崩溃的情况,请发表评论。 Thank you!
谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.