Day6-DialogFragment & AlertDialog

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

用法

自定义布局

  1. 创建布局文件

    <?xml version="1.0" encoding="utf-8"?>  
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content" >  
    
        <TextView  
            android:id="@+id/id_label_your_name"  
            android:layout_width="wrap_content"  
            android:layout_height="32dp"  
            android:gravity="center_vertical"  
            android:text="Your name:" />  
    
        <EditText  
            android:id="@+id/id_txt_your_name"  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content"  
            android:layout_toRightOf="@id/id_label_your_name"  
            android:imeOptions="actionDone"  
            android:inputType="text" />  
    
        <Button  
            android:id="@+id/id_sure_edit_name"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:layout_alignParentRight="true"  
            android:layout_below="@id/id_txt_your_name"  
            android:text="ok" />  
    
    </RelativeLayout>  
    
  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. 布局不需要添加按钮
    <?xml version="1.0" encoding="utf-8"?>  
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content" >  
    
        <TextView  
            android:id="@+id/id_label_your_name"  
            android:layout_width="wrap_content"  
            android:layout_height="32dp"  
            android:gravity="center_vertical"  
            android:text="Your name:" />  
    
        <EditText  
            android:id="@+id/id_txt_your_name"  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content"  
            android:layout_toRightOf="@id/id_label_your_name"  
            android:imeOptions="actionDone"  
            android:inputType="text" />  
    
        <Button  
            android:id="@+id/id_sure_edit_name"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:layout_alignParentRight="true"  
            android:layout_below="@id/id_txt_your_name"  
            android:text="ok" />  
    
    </RelativeLayout>  
    
  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不消失
     }
    

参考

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,982评论 25 708
  • 本人初学Android,最近做了一个实现安卓简单音乐播放功能的播放器,收获不少,于是便记录下来自己的思路与知识总结...
    落日柳风阅读 19,211评论 2 41
  • “这个周末想做绿茶戚风吗?” “好啊!”姐姐一听,马上兴奋起来。 “那先给我收拾好玩具,然后帮忙洗衣服,完了才可以...
    二十五岁的老奶奶阅读 577评论 13 8
  • 1、晚上看到一位简书朋友写的<<父亲走了>>,深有感触。我父亲在我十二岁的时候就走了,那时候我年少无知,真没有什么...
    台州韩瑛阅读 202评论 0 0
  • 我想你对这样的故事并不陌生 :年轻有为的大学在校生窝在宿舍里开创未来 ;他们天马行空 ,掌握新科技 ,满怀激情 ,...
    东方不嫁阅读 278评论 0 0