DialogFragment 使用整理

为什么使用DialogFragment

  1. 可以在屏幕旋转或按下返回键可以更好的处理其生命周期
  2. 在平板中可以将其嵌入在UI中,类似传统的fragment的使用

怎么使用DialogFragment

  1. 重写onCreateView()方法
```
 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;  
    }  
}
```
  1. 重写onCreateDialog()方法
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();
  }
  }
  1. 调用方式
  MyDialogFragment fragment= new MyDialogFragment ();  
  fragment.show(getFragmentManager(), "MyDialogment");
  1. 可根据屏幕尺寸决定将fragment显示为对话框还是全屏
public void showDialog() {
  FragmentManager fragmentManager = getSupportFragmentManager();
  CustomDialogFragment newFragment = new CustomDialogFragment();

  if (mIsLargeLayout) {
      // The device is using a large layout, so show the fragment as a dialog
      newFragment.show(fragmentManager, "dialog");
  } else {
      // The device is smaller, so show the fragment fullscreen
      FragmentTransaction transaction = fragmentManager.beginTransaction();
      // For a little polish, specify a transition animation
      transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
      // To make it fullscreen, use the 'content' root view as the container
      // for the fragment, which is always the root view for the activity
      transaction.add(android.R.id.content, newFragment)
                 .addToBackStack(null).commit();
  }
}

事件传递

  1. 宿主为activity

    官方指南中是通过fragment的onAttach()方法,将activity强转为回调listener.

```
public class NoticeDialogFragment extends DialogFragment {
  public interface NoticeDialogListener {
      public void onDialogPositiveClick(DialogFragment dialog);
      public void onDialogNegativeClick(DialogFragment dialog);
  }
  @Override
  public void onAttach(Activity activity) {
      super.onAttach(activity);
      try {
          mListener = (NoticeDialogListener) activity;
      } catch (ClassCastException e) {
          // The activity doesn't implement the interface, throw exception
          throw new ClassCastException(activity.toString()
                  + " must implement NoticeDialogListener");
      }
  }
}
```
> 宿主通过实现listener,来完成回调

```
public class MainActivity extends FragmentActivity
                      implements NoticeDialogFragment.NoticeDialogListener{
  public void showNoticeDialog() {
      DialogFragment dialog = new NoticeDialogFragment();
      dialog.show(getSupportFragmentManager(), "NoticeDialogFragment");
  }
  @Override
  public void onDialogPositiveClick(DialogFragment dialog) {
  }
  @Override
  public void onDialogNegativeClick(DialogFragment dialog) {
  }
}
```
  1. 宿主为fragment
> 通过fragment的onActivityResult方法来进行回调,需要设置targetFragment
宿主设置
```
public class HostFragment extends Fragment{
  //开启dialog
  public void showDialog{
    MyDialogFragment fragment= new MyDialogFragment();  
    fragment.setTargetFragment(context, REQUEST_CODE);
    fragment.show(getFragmentManager(), "MyDialogment");
  }
  //宿主回调
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE:
                  //do something
                    break;
            }
        }
    }
}
```
调用回调
```
getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK,       data);
```
  1. 混合情况.作为一个common的dialog
> 参考[Android DialogFragment 在页面销毁下的使用方式 \- ](http://www.jianshu.com/p/5ba9f36a4a90)

疑难杂症

  1. 调用show方法的时候会出现IllegalStateException
    具体原因可见 记一个DialogFragment.show()的Bug -
```
//重写show方法加入try/catch
public class BaseDialogFragment extends AppCompatDialogFragment {
    @Override
    public void show(FragmentManager manager, String tag) {
        try {
            super.show(manager, tag);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }
}
```

你可能感兴趣的:(DialogFragment 使用整理)