Day6-DialogFragment & AlertDialog

Google 在官方文档中已经默认DialogFragment作为对话框的容器, 在其中填入AlertDialog或DatePickerDialog/ TimePickerDialog
  • 优点: DialogFragment 能依靠 activity 的 onSaveInstance 和 FragmentManager 在横竖屏切换等 Activity 被杀死重建时重建对话框
  • 缺点: TargetVersion 需定到 APILevel 11

用法

自定义布局

  1. 创建布局文件

      
      
    
          
    
          
    
        
  2. 继承DialogFragment,重写onCreagteView

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_dialog, container);
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉默认标题
        return inflate;
    }
    
  3. 在 activity中调用

    EditDialogFragment editDialogFragment = new EditDialogFragment();
    editDialogFragment.show(getFragmentManager(), "EditNameDialog");
    

默认的dialog格式, 按钮具体的样式跟着系统版本变化

  1. 布局不需要添加按钮
      
      
    
          
    
          
    
        
  2. 重写onCreateDialog
    onAttach 拿到上下文, 判断后强转成 Listener
    public class NoticeDialogFragment extends DialogFragment {
    
        /* The activity that creates an instance of this dialog fragment must
         * implement this interface in order to receive event callbacks.
         * Each method passes the DialogFragment in case the host needs to query it. */
        public interface NoticeDialogListener {
            public void onDialogPositiveClick(DialogFragment dialog);
            public void onDialogNegativeClick(DialogFragment dialog);
        }
    
        // Use this instance of the interface to deliver action events
        NoticeDialogListener mListener;
    
        // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            // Verify that the host activity implements the callback interface
            try {
                // Instantiate the NoticeDialogListener so we can send events to the host
                mListener = (NoticeDialogListener) context;
            } catch (ClassCastException e) {
                // The activity doesn't implement the interface, throw exception
                throw new ClassCastException(context.toString()
                        + " must implement NoticeDialogListener");
            }
        }
        ...
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
               // Build the dialog and set up the button click handlers
               AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
               builder.setMessage(R.string.dialog_fire_missiles)
                      .setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
                          public void onClick(DialogInterface dialog, int id) {
                              // Send the positive button event back to the host activity
                              mListener.onDialogPositiveClick(NoticeDialogFragment.this);
                          }
                      })
                      .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                          public void onClick(DialogInterface dialog, int id) {
                              // Send the negative button event back to the host activity
                              mListener.onDialogNegativeClick(NoticeDialogFragment.this);
                          }
                      });
               return builder.create();
           }
        }
    
    }
    
  3. 调用
    DialogFragment newFragment = new FireMissilesDialogFragment();
    newFragment.show(getSupportFragmentManager(), "missiles");
    
  4. 数据传递, 在 Activity 继承接口, 实现方法
    public class MainActivity extends FragmentActivity
                                implements NoticeDialogFragment.NoticeDialogListener{
          ...
    
          public void showNoticeDialog() {
              // Create an instance of the dialog fragment and show it
              DialogFragment dialog = new NoticeDialogFragment();
              dialog.show(getSupportFragmentManager(), "NoticeDialogFragment");
          }
    
          // The dialog fragment receives a reference to this Activity through the
          // Fragment.onAttach() callback, which it uses to call the following methods
          // defined by the NoticeDialogFragment.NoticeDialogListener interface
          @Override
          public void onDialogPositiveClick(DialogFragment dialog) {
              // User touched the dialog's positive button
              dialog.getdialog.findViewById...
              ...
          }
    
          @Override
          public void onDialogNegativeClick(DialogFragment dialog) {
              // User touched the dialog's negative button
              ...
          }
      }
    

清除对话框

手动调dismiss();

默认AlertDialog, 改button颜色

show(), 之后再getButton

AlertDialog alertdialog = new AlertDialog.Builder(getActivity()).create();
       LayoutInflater layoutInflater = getActivity().getLayoutInflater();
       View view = layoutInflater.inflate(R.layout.fragment_dialog, null);
       alertdialog.setView(view);
       alertdialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
           @Override
           public void onClick(DialogInterface dialog, int which) {

           }
       });
       alertdialog.setButton(DialogInterface.BUTTON_POSITIVE, "ok", new DialogInterface.OnClickListener() {
           @Override
           public void onClick(DialogInterface dialog, int which) {

           }
       });
       alertdialog.show();
       Button button = alertdialog.getButton(alertdialog.BUTTON_POSITIVE);
       button.setTextColor(Color.parseColor("#00ffff"));
       return alertdialog;

不可点击

  • 通用
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    //        this.setCancelable(false);
    }
    
  • dialog的另一种方式
     public Dialog onCreateDialog(Bundle savedInstanceState) {  
        dialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
     }
    

参考

  • CSDN | Android 官方推荐 : DialogFragment 创建对话框
  • | [Android] Material 风格的 Dialog 的使用的第七条评论
  • CSDN | 从源码看 AlertDialog.getButton(DialogInterface.BUTTON_POSITIVE) 为什么是 null

你可能感兴趣的:(Day6-DialogFragment & AlertDialog)