DialogFragment是从Activity还是Fragment打开的?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DialogFragment是从Activity还是Fragment打开的?相关的知识,希望对你有一定的参考价值。
我想检测是否从Activity或Fragment打开DialogFragment。因为调用Activity或Fragment将为侦听器附加一个接口。
如果Activity用于显示对话框:(在DialogFragment里面我会写)
listener = (MyListener) getActivity();
否则,如果Fragment正在调用对话框:
listener = (MyListener) getParentFragment;
所以,我需要检测谁在调用对话框片段!
答案
If you ask me to edit your code then do this.
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;
}
}
If you ask me a suggestion - Pass listener instead of checking from Activity or Fragment.
您应该使用setter来执行常用代码,以便将来可以传递侦听器。
DialogFragment newFragment = new MyAlertDialogFragment();
newFragment.setListener(this); // or use anonymous deriving like new Listener()...
另一答案
我使用以下样式作为我的问题,发布作为答案,因为它可能会帮助某人。
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..
}
并从Any Activity或Fragment调用
活动
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;
}
}
如果有任何可能的错误或可能崩溃的情况,请评论。谢谢!
以上是关于DialogFragment是从Activity还是Fragment打开的?的主要内容,如果未能解决你的问题,请参考以下文章
试图将数据从 DialogFragment 传递回父 Activity
用全屏DialogFragment代替Activity,结合ViewPager展示图片
底部弹出DialogFragment+与Activity数据交互