Day6-DialogFragment & AlertDialog

Google 在官方文檔中已經(jīng)默認DialogFragment作為對話框的容器, 在其中填入AlertDialog或DatePickerDialog/ TimePickerDialog
  • 優(yōu)點: DialogFragment 能依靠 activity 的 onSaveInstance 和 FragmentManager 在橫豎屏切換等 Activity 被殺死重建時重建對話框
  • 缺點: TargetVersion 需定到 APILevel 11

用法

自定義布局

  1. 創(chuàng)建布局文件

    <?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格式, 按鈕具體的樣式跟著系統(tǒng)版本變化

  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. 數(shù)據(jù)傳遞, 在 Activity 繼承接口, 實現(xiàn)方法
    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不消失
     }
    

參考

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,041評論 25 709
  • 本人初學Android,最近做了一個實現(xiàn)安卓簡單音樂播放功能的播放器,收獲不少,于是便記錄下來自己的思路與知識總結...
    落日柳風閱讀 19,454評論 2 41
  • “這個周末想做綠茶戚風嗎?” “好啊!”姐姐一聽,馬上興奮起來。 “那先給我收拾好玩具,然后幫忙洗衣服,完了才可以...
    二十五歲的老奶奶閱讀 642評論 13 8
  • 1、晚上看到一位簡書朋友寫的<<父親走了>>,深有感觸。我父親在我十二歲的時候就走了,那時候我年少無知,真沒有什么...
    臺州韓瑛閱讀 233評論 0 0
  • 我想你對這樣的故事并不陌生 :年輕有為的大學在校生窩在宿舍里開創(chuàng)未來 ;他們天馬行空 ,掌握新科技 ,滿懷激情 ,...
    東方不嫁閱讀 306評論 0 0

友情鏈接更多精彩內容