1. 程式人生 > >Android基礎 ------- Android八大對話方塊

Android基礎 ------- Android八大對話方塊

Android對話方塊

普通Dialog(圖1與圖2)
列表Dialog(圖3)
單選Dialog(圖4)
多選Dialog(圖5)
等待Dialog(圖6)
進度條Dialog(圖7)
編輯Dialog(圖8)
自定義Dialog(圖9)

這裡寫圖片描述

1.普通對話方塊

最簡單的

 AlertDialog dialog = new AlertDialog.Builder(this)
                .setIcon(R.mipmap.icon)//設定標題的圖片
                .setTitle("我是對話方塊"
)//設定對話方塊的標題 .setMessage("我是對話方塊的內容")//設定對話方塊的內容 //設定對話方塊的按鈕 .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(MainActivity.this
, "點選了取消按鈕", Toast.LENGTH_SHORT).show(); dialog.dismiss(); } }) .setPositiveButton("確定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int
which) { Toast.makeText(MainActivity.this, "點選了確定的按鈕", Toast.LENGTH_SHORT).show(); dialog.dismiss(); } }).create(); dialog.show();

AlertDialog類中有一個靜態內部類Builder。所以可以看出對話方塊使用了一個建造者模式在呼叫函式的時候就可以一直直點點點鏈式呼叫。 需要注意的是:NegativeButton這個按鈕是在對話方塊的左邊,PositiveButton在對話方塊的右邊;如果你還想再加一個按鈕也是可以的只需要在呼叫.setNeutralButton(“第三個按鈕”,listener)即可。

圖一

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button buttonNormal = (Button) findViewById(R.id.button_normal);
        buttonNormal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showNormalDialog();
            }
        });
    }

    private void showNormalDialog(){
        /* @setIcon 設定對話方塊圖示
         * @setTitle 設定對話方塊標題
         * @setMessage 設定對話方塊訊息提示
         * setXXX方法返回Dialog物件,因此可以鏈式設定屬性
         */
        final AlertDialog.Builder normalDialog = 
            new AlertDialog.Builder(MainActivity.this);
        normalDialog.setIcon(R.drawable.icon_dialog);
        normalDialog.setTitle("我是一個普通Dialog")
        normalDialog.setMessage("你要點選哪一個按鈕呢?");
        normalDialog.setPositiveButton("確定", 
            new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //...To-do
            }
        });
        normalDialog.setNegativeButton("關閉", 
            new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //...To-do
            }
        });
        // 顯示
        normalDialog.show();
    }
}

圖二

/* @setNeutralButton 設定中間的按鈕
 * 若只需一個按鈕,僅設定 setPositiveButton 即可
 */
private void showMultiBtnDialog(){
    AlertDialog.Builder normalDialog = 
        new AlertDialog.Builder(MainActivity.this);
    normalDialog.setIcon(R.drawable.icon_dialog);
    normalDialog.setTitle("我是一個普通Dialog").setMessage("你要點選哪一個按鈕呢?");
    normalDialog.setPositiveButton("按鈕1", 
        new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // ...To-do
        }
    });
    normalDialog.setNeutralButton("按鈕2", 
        new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // ...To-do
        }
    });
    normalDialog.setNegativeButton("按鈕3", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // ...To-do
        }
    });
    // 建立例項並顯示
    normalDialog.show();
}

2. 列表對話方塊

當給使用者的選擇就那麼幾條路的時候,就可在對話方塊上放置一個列表供使用者自己選擇

圖三

private void showListDialog() {
    final String[] items = { "我是1","我是2","我是3","我是4" };
    AlertDialog.Builder listDialog = 
        new AlertDialog.Builder(MainActivity.this);
    listDialog.setTitle("我是一個列表Dialog");
    listDialog.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // which 下標從0開始
            // ...To-do
            Toast.makeText(MainActivity.this, 
                "你點選了" + items[which], 
                Toast.LENGTH_SHORT).show();
        }
    });
    listDialog.show();
}
------------------------------------------------------------------------------

//案列二
   final String items[] = {"我是Item一", "我是Item二", "我是Item三", "我是Item四"};
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setIcon(R.mipmap.icon)//設定標題的圖片
                .setTitle("列表對話方塊")//設定對話方塊的標題
                .setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, items[which], Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("確定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();

3.單選對話方塊

圖四

int yourChoice;
private void showSingleChoiceDialog(){
    final String[] items = { "我是1","我是2","我是3","我是4" };
    yourChoice = -1;
    AlertDialog.Builder singleChoiceDialog = 
        new AlertDialog.Builder(MainActivity.this);
    singleChoiceDialog.setTitle("我是一個單選Dialog");
    // 第二個引數是預設選項,此處設定為0
    singleChoiceDialog.setSingleChoiceItems(items, 0, 
        new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            yourChoice = which;
        }
    });
    singleChoiceDialog.setPositiveButton("確定", 
        new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (yourChoice != -1) {
                Toast.makeText(MainActivity.this, 
                "你選擇了" + items[yourChoice], 
                Toast.LENGTH_SHORT).show();
            }
        }
    });
    singleChoiceDialog.show();
}


-----------------------------------------------------------------------------
//案例二

final String items[] = {"我是Item一", "我是Item二", "我是Item三", "我是Item四"};
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setIcon(R.mipmap.icon)//設定標題的圖片
                .setTitle("單選列表對話方塊")//設定對話方塊的標題
                //setSingleChoiceItems第一個引數:設定單選的資源陣列;第二個引數:設定預設選中哪一項。
                .setSingleChoiceItems(items, 1, new DialogInterface.OnClickListener() { 
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, items[which], Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("確定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();

4 .多選對話方塊

圖五

ArrayList<Integer> yourChoices = new ArrayList<>();
private void showMultiChoiceDialog() {
    final String[] items = { "我是1","我是2","我是3","我是4" };
    // 設定預設選中的選項,全為false預設均未選中
    final boolean initChoiceSets[]={false,false,false,false};
    yourChoices.clear();
    AlertDialog.Builder multiChoiceDialog = 
        new AlertDialog.Builder(MainActivity.this);
    multiChoiceDialog.setTitle("我是一個多選Dialog");
    multiChoiceDialog.setMultiChoiceItems(items, initChoiceSets,
        new DialogInterface.OnMultiChoiceClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which,
            boolean isChecked) {
            if (isChecked) {
                yourChoices.add(which);
            } else {
                yourChoices.remove(which);
            }
        }
    });
    multiChoiceDialog.setPositiveButton("確定", 
        new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            int size = yourChoices.size();
            String str = "";
            for (int i = 0; i < size; i++) {
                str += items[yourChoices.get(i)] + " ";
            }
            Toast.makeText(MainActivity.this, 
                "你選中了" + str, 
                Toast.LENGTH_SHORT).show();
        }
    });
    multiChoiceDialog.show();
}


---------------------------------------------------------------------
案例二
final String items[] = {"我是Item一", "我是Item二", "我是Item三", "我是Item四"};
        final boolean checkedItems[] = {true, false, true, false};
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setIcon(R.mipmap.icon)//設定標題的圖片
                .setTitle("多選對話方塊")//設定對話方塊的標題
                //setMultiChoiceItems(items, checkedItems, listener)//第一個引數:設定單選的資源;第二個引數:設定預設選中哪幾項(陣列);
                .setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                        checkedItems[which] = isChecked;
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("確定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        for (int i = 0; i < checkedItems.length; i++) {
                            if (checkedItems[i]) {
                                Toast.makeText(MainActivity.this, "選中了" + i, Toast.LENGTH_SHORT).show();
                            }
                        }
                        dialog.dismiss();
                    }

                }).create();

        dialog.show();

5.等待對話方塊

圖六

private void showWaitingDialog() {
    /* 等待Dialog具有遮蔽其他控制元件的互動能力
     * @setCancelable 為使螢幕不可點選,設定為不可取消(false)
     * 下載等事件完成後,主動呼叫函式關閉該Dialog
     */
    ProgressDialog waitingDialog= 
        new ProgressDialog(MainActivity.this);
    waitingDialog.setTitle("我是一個等待Dialog");
    waitingDialog.setMessage("等待中...");
    waitingDialog.setIndeterminate(true);
    waitingDialog.setCancelable(false);
    waitingDialog.show();
}

------------------------------------------------------------------------
//案例二:
 ProgressDialog dialog = new ProgressDialog(this);
 dialog.setMessage("正在載入中");
 dialog.show();

6.進度條對話方塊

圖七

private void showProgressDialog() {
    /* @setProgress 設定初始進度
     * @setProgressStyle 設定樣式(水平進度條)
     * @setMax 設定進度最大值
     */
    final int MAX_PROGRESS = 100;
    final ProgressDialog progressDialog = 
        new ProgressDialog(MainActivity.this);
    progressDialog.setProgress(0);
    progressDialog.setTitle("我是一個進度條Dialog");
    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    progressDialog.setMax(MAX_PROGRESS);
    progressDialog.show();
    /* 模擬進度增加的過程
     * 新開一個執行緒,每個100ms,進度增加1
     */
    new Thread(new Runnable() {
        @Override
        public void run() {
            int progress= 0;
            while (progress < MAX_PROGRESS){
                try {
                    Thread.sleep(100);
                    progress++;
                    progressDialog.setProgress(progress);
                } catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
            // 進度達到最大值後,視窗消失
            progressDialog.cancel();
        }
    }).start();
}


--------------------------------------------------------------------------------
//案例二
  final ProgressDialog dialog = new ProgressDialog(this);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setMessage("正在載入中");
        dialog.setMax(100);
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            int progress = 0;

            @Override
            public void run() {
                dialog.setProgress(progress += 5);
                if (progress == 100) {
                    timer.cancel();
                }
            }
        }, 0, 1000);
        dialog.show();

7.編輯Dialog

圖八

private void showInputDialog() {
    /*@setView 裝入一個EditView
     */
    final EditText editText = new EditText(MainActivity.this);
    AlertDialog.Builder inputDialog = 
        new AlertDialog.Builder(MainActivity.this);
    inputDialog.setTitle("我是一個輸入Dialog").setView(editText);
    inputDialog.setPositiveButton("確定", 
        new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(MainActivity.this,
            editText.getText().toString(), 
            Toast.LENGTH_SHORT).show();
        }
    }).show();
}

8:自定義對話方塊

圖九

(1)方法一

 //1.自定義View

<!-- res/layout/dialog_customize.xml-->
<!-- 自定義View -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        />
</LinearLayout>
  //2.使用setView將自定的view裝入AlertDialog,並設定樣式
private void showCustomizeDialog() {
    /* @setView 裝入自定義View ==> R.layout.dialog_customize
     * 由於dialog_customize.xml只放置了一個EditView,因此和圖8一樣
     * dialog_customize.xml可自定義更復雜的View
     */
    AlertDialog.Builder customizeDialog = 
        new AlertDialog.Builder(MainActivity.this);
    final View dialogView = LayoutInflater.from(MainActivity.this)
        .inflate(R.layout.dialog_customize,null);
    customizeDialog.setTitle("我是一個自定義Dialog");
    customizeDialog.setView(dialogView);
    customizeDialog.setPositiveButton("確定",
        new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // 獲取EditView中的輸入內容
            EditText edit_text = 
                (EditText) dialogView.findViewById(R.id.edit_text);
            Toast.makeText(MainActivity.this,
                edit_text.getText().toString(),
                Toast.LENGTH_SHORT).show();
        }
    });
    customizeDialog.show();
}
//3.複寫回撥函式
/* 複寫Builder的create和show函式,可以在Dialog顯示前實現必要設定
 * 例如初始化列表、預設選項等
 * @create 第一次建立時呼叫
 * @show 每次顯示時呼叫
 */
private void showListDialog() {
    final String[] items = { "我是1","我是2","我是3","我是4" };
    AlertDialog.Builder listDialog = 
        new AlertDialog.Builder(MainActivity.this){

        @Override
        public AlertDialog create() {
            items[0] = "我是No.1";
            return super.create();
        }

        @Override
        public AlertDialog show() {
            items[1] = "我是No.2";
            return super.show();
        }
    };
    listDialog.setTitle("我是一個列表Dialog");
    listDialog.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // ...To-do
        }
    });
    /* @setOnDismissListener Dialog銷燬時呼叫
     * @setOnCancelListener Dialog關閉時呼叫
     */
    listDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
        public void onDismiss(DialogInterface dialog) {
            Toast.makeText(getApplicationContext(),
                "Dialog被銷燬了", 
                Toast.LENGTH_SHORT).show();
        }
    });
    listDialog.show();
}

(2)方法二

首先我們需要自定義Dialog的style,讓他自己本有的東西全部透明,然後在設定我們自己的內容就可以達到完全自定義的效果了。

  <!--對話方塊的樣式-->
    <style name="NormalDialogStyle">
        <!--對話方塊背景 -->
        <item name="android:windowBackground">@android:color/transparent</item>
        <!--邊框 -->
        <item name="android:windowFrame">@null</item>
        <!--沒有標題 -->
        <item name="android:windowNoTitle">true</item>
        <!-- 是否浮現在Activity之上 -->
        <item name="android:windowIsFloating">true</item>
        <!--背景透明 -->
        <item name="android:windowIsTranslucent">false</item>
        <!-- 是否有覆蓋 -->
        <item name="android:windowContentOverlay">@null</item>
        <!--進出的顯示動畫 -->
        <item name="android:windowAnimationStyle">@style/normalDialogAnim</item>
        <!--背景變暗-->
        <item name="android:backgroundDimEnabled">true</item>
    </style>
    <!--對話方塊動畫-->
    <style name="normalDialogAnim" parent="android:Animation">
        <item name="@android:windowEnterAnimation">@anim/normal_dialog_enter</item>
        <item name="@android:windowExitAnimation">@anim/normal_dialog_exit</item>
    </style>

接下來就可以為對話方塊設定我們自定義的style了.

   /**
     * 自定義對話方塊
     */
    private void customDialog() {
        final Dialog dialog = new Dialog(this, R.style.NormalDialogStyle);
        View view = View.inflate(this, R.layout.dialog_normal, null);
        TextView cancel = (TextView) view.findViewById(R.id.cancel);
        TextView confirm = (TextView) view.findViewById(R.id.confirm);
        dialog.setContentView(view);
        //使得點選對話方塊外部不消失對話方塊
        dialog.setCanceledOnTouchOutside(true);
        //設定對話方塊的大小
        view.setMinimumHeight((int) (ScreenSizeUtils.getInstance(this).getScreenHeight() * 0.23f));
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (ScreenSizeUtils.getInstance(this).getScreenWidth() * 0.75f);
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        dialogWindow.setAttributes(lp);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }