为何使用DialogFragment?

问题的由来

最近在优化项目代码时,项目中创建对话框一般使用的是Dialog,AlertDialog。
但是当Dialog中View界面复杂、逻辑复杂时,导致当前页面既要写自己的页面逻辑,还要写Dialog中的逻辑。
官方推出了DialogFragment来代替Dialog,那我就去了解了下DialogFragment的使用。

DialogFragment的优点

  • DialogFragment说到底还是一个Fragment,因此它继承了Fragment的所有特性。
    同理FragmentManager会管理DialogFragment。
  • 可以在屏幕旋转或按下返回键可以更好的处理其生命周期。
  • 在手机配置发生变化的时候,FragmentManager可以负责现场的恢复工作。
    调用DialogFragment的setArguments(bundle)方法进行数据的设置,可以保证DialogFragment的数据也能恢复。
  • DialogFragment里的onCreateView和onCreateDIalog 2个方法,onCreateView可以用来创建自定义Dialog,onCreateDIalog 可以用Dialog来创建系统原生Dialog。可以在一个类中管理2种不同的dialog。

DialogFragment使用

1. 创建DialogFragment

DialogFragment至少需要实现onCreateView或者onCreateDIalog方法中的一个。

  • 重写onCreateView()方法,可以用来创建自定义Dialog
public class MyDialogFragment extends DialogFragment  {
   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container,
           Bundle savedInstanceState){
       View view = inflater.inflate(R.layout.fragment_dialog, container);
       return view;
   }
}

  • 重写onCreateDialog()方法,创建系统原生Dialog
public class MyDialogFragment extends DialogFragment  {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
     AlertDialog.Builder builder = new AlertDialog.Builder(getContext(),R.style.theme);
     builder.setTitle("对话框");
     View view = inflater.inflate(R.layout.fragment_dialog, container);
     builder.setView(view);
     builder.setPositiveButton("确定", null);
     builder.setNegativeButton("取消", null);
     return builder.create();
 }
}
2. 调用方式
MyDialogFragment fragment= new MyDialogFragment ();
fragment.show(getFragmentManager(), "MyDialogment");

关于fragment和activity之间进行通信可以使用接口回调的方式

DialogFragment的扩展

  • 设置宽高和对话框背景等

    在xml中设置和onCreateView(), onViewCreated()中设置无效. 在onStart()和onResume()中设置才有效.

@Override
public void onStart() { //在onStart()中
    super.onStart();
    getDialog().getWindow().setBackgroundDrawableResource(R.drawable.background); //对话框背景
    getDialog().getWindow().setLayout(300,200); //宽高
}
  • 向DialogFragment传递参数
public static MyDialogFragment newInstance(int num) {
        MyDialogFragment f = new MyDialogFragment();
        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt("num", num);
        f.setArguments(args);
        return f;
    }

参考文献

  • Android DialogFragment简介
  • DialogFragment 使用整理
  • Android:我为何要封装DialogFragment?
  • DialogFragment使用时遇到的一些问题

你可能感兴趣的:(为何使用DialogFragment?)