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不消失
     }
    

参考

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,470评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,393评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,577评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,176评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,189评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,155评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,041评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,903评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,319评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,539评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,703评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,417评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,013评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,664评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,818评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,711评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,601评论 2 353

推荐阅读更多精彩内容

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