## 本節引言:
> 本節繼續給大家帶來是顯示提示信息的第三個控件AlertDialog(對話框),同時它也是其他 Dialog的的父類!比如ProgressDialog,TimePickerDialog等,而AlertDialog的父類是:Dialog! 另外,不像前面學習的Toast和Notification,AlertDialog并不能直接new出來,如果你打開 AlertDialog的源碼,會發現構造方法是protected的,如果我們要創建AlertDialog的話,我們 需要使用到該類中的一個靜態內部類:public static class?**Builder**,然后來調用AlertDialog 里的相關方法,來對AlertDialog進行定制,最后調用show()方法來顯示我們的AlertDialog對話框! 好的,下面我們就來學習AlertDialog的基本用法,以及定制我們的AlertDialog! 官方文檔:[AlertDialog](http://androiddoc.qiniudn.com/reference/android/app/AlertDialog.html)
* * *
## 1.基本使用流程
> * **Step 1**:創建**AlertDialog.Builder**對象;
> * **Step 2**:調用**setIcon()**設置圖標,**setTitle()**或**setCustomTitle()**設置標題;
> * **Step 3**:設置對話框的內容:**setMessage()**還有其他方法來指定顯示的內容;
> * **Step 4**:調用**setPositive/Negative/NeutralButton()**設置:確定,取消,中立按鈕;
> * **Step 5**:調用**create()**方法創建這個對象,再調用**show()**方法將對話框顯示出來;
* * *
## 2.幾種常用的對話框使用示例
**運行效果圖:**

**核心代碼**:
**MainActivity.java**:
~~~
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_dialog_one;
private Button btn_dialog_two;
private Button btn_dialog_three;
private Button btn_dialog_four;
private Context mContext;
private boolean[] checkItems;
private AlertDialog alert = null;
private AlertDialog.Builder builder = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = MainActivity.this;
bindView();
}
private void bindView() {
btn_dialog_one = (Button) findViewById(R.id.btn_dialog_one);
btn_dialog_two = (Button) findViewById(R.id.btn_dialog_two);
btn_dialog_three = (Button) findViewById(R.id.btn_dialog_three);
btn_dialog_four = (Button) findViewById(R.id.btn_dialog_four);
btn_dialog_one.setOnClickListener(this);
btn_dialog_two.setOnClickListener(this);
btn_dialog_three.setOnClickListener(this);
btn_dialog_four.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
//普通對話框
case R.id.btn_dialog_one:
alert = null;
builder = new AlertDialog.Builder(mContext);
alert = builder.setIcon(R.mipmap.ic_icon_fish)
.setTitle("系統提示:")
.setMessage("這是一個最普通的AlertDialog,\n帶有三個按鈕,分別是取消,中立和確定")
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(mContext, "你點擊了取消按鈕~", Toast.LENGTH_SHORT).show();
}
})
.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(mContext, "你點擊了確定按鈕~", Toast.LENGTH_SHORT).show();
}
})
.setNeutralButton("中立", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(mContext, "你點擊了中立按鈕~", Toast.LENGTH_SHORT).show();
}
}).create(); //創建AlertDialog對象
alert.show(); //顯示對話框
break;
//普通列表對話框
case R.id.btn_dialog_two:
final String[] lesson = new String[]{"語文", "數學", "英語", "化學", "生物", "物理", "體育"};
alert = null;
builder = new AlertDialog.Builder(mContext);
alert = builder.setIcon(R.mipmap.ic_icon_fish)
.setTitle("選擇你喜歡的課程")
.setItems(lesson, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "你選擇了" + lesson[which], Toast.LENGTH_SHORT).show();
}
}).create();
alert.show();
break;
//單選列表對話框
case R.id.btn_dialog_three:
final String[] fruits = new String[]{"蘋果", "雪梨", "香蕉", "葡萄", "西瓜"};
alert = null;
builder = new AlertDialog.Builder(mContext);
alert = builder.setIcon(R.mipmap.ic_icon_fish)
.setTitle("選擇你喜歡的水果,只能選一個哦~")
.setSingleChoiceItems(fruits, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "你選擇了" + fruits[which], Toast.LENGTH_SHORT).show();
}
}).create();
alert.show();
break;
//多選列表對話框
case R.id.btn_dialog_four:
final String[] menu = new String[]{"水煮豆腐", "蘿卜牛腩", "醬油雞", "胡椒豬肚雞"};
//定義一個用來記錄個列表項狀態的boolean數組
checkItems = new boolean[]{false, false, false, false};
alert = null;
builder = new AlertDialog.Builder(mContext);
alert = builder.setIcon(R.mipmap.ic_icon_fish)
.setMultiChoiceItems(menu, checkItems, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
checkItems[which] = isChecked;
}
})
.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String result = "";
for (int i = 0; i < checkItems.length; i++) {
if (checkItems[i])
result += menu[i] + " ";
}
Toast.makeText(getApplicationContext(), "客官你點了:" + result, Toast.LENGTH_SHORT).show();
}
})
.create();
alert.show();
break;
}
}
}
~~~
布局就是四個簡單的按鈕,這里就不貼出來了,用法非常簡單~無非就是創建一個Builder對象后, 進行相關設置,然后create()生成一個AlertDialog對象,最后調用show()方法將AlertDialog 顯示出來而已!另外,細心的你可能發現我們點擊對話框的外部區域,對話框就會消失,我們 可以為builder設置**setCancelable(false)**即可解決這個問題!
* * *
## 3.通過Builder的setView()定制顯示的AlertDialog
> 我們可以自定義一個與系統對話框不同的布局,然后調用setView()將我們的布局加載到 AlertDialog上,上面我們來實現這個效果:
**運行效果圖**:

**關鍵代碼**:
首先是兩種不同按鈕的selctor的drawable文件:
**btn_selctor_exit.xml**:
~~~
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@mipmap/iv_icon_exit_pressed"/>
<item android:drawable="@mipmap/iv_icon_exit_normal"/>
</selector>
~~~
**btn_selctor_choose.xml**:
~~~
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@mipmap/bg_btn_pressed"/>
<item android:drawable="@mipmap/bg_btn_normal"/>
</selector>
~~~
接著是自定義的Dialog布局:**view_dialog_custom.xml**:
~~~
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:id="@+id/titlelayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#53CC66"
android:padding="5dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="提示信息"
android:textColor="#ffffff"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="@+id/btn_cancle"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:background="@drawable/btn_selctor_exit" />
</RelativeLayout>
<LinearLayout
android:id="@+id/ly_detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/titlelayout"
android:layout_centerInParent="true"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:text="通過setView()方法定制AlertDialog"
android:textColor="#04AEDA"
android:textSize="18sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="作者:Coder-pig"
android:textColor="#04AEDA"
android:textSize="18sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/ly_detail"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<Button
android:id="@+id/btn_blog"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@drawable/btn_selctor_choose"
android:text="訪問博客"
android:textColor="#ffffff"
android:textSize="20sp" />
<Button
android:id="@+id/btn_close"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@drawable/btn_selctor_choose"
android:text="關閉"
android:textColor="#ffffff"
android:textSize="20sp" />
</LinearLayout>
</RelativeLayout>
~~~
最后是**MainActivity.java**:
~~~
public class MainActivity extends AppCompatActivity {
private Button btn_show;
private View view_custom;
private Context mContext;
private AlertDialog alert = null;
private AlertDialog.Builder builder = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = MainActivity.this;
btn_show = (Button) findViewById(R.id.btn_show);
//初始化Builder
builder = new AlertDialog.Builder(mContext);
//加載自定義的那個View,同時設置下
final LayoutInflater inflater = MainActivity.this.getLayoutInflater();
view_custom = inflater.inflate(R.layout.view_dialog_custom, null,false);
builder.setView(view_custom);
builder.setCancelable(false);
alert = builder.create();
view_custom.findViewById(R.id.btn_cancle).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
alert.dismiss();
}
});
view_custom.findViewById(R.id.btn_blog).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "訪問博客", Toast.LENGTH_SHORT).show();
Uri uri = Uri.parse("http://blog.csdn.net/coder_pig");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
alert.dismiss();
}
});
view_custom.findViewById(R.id.btn_close).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "對話框已關閉~", Toast.LENGTH_SHORT).show();
alert.dismiss();
}
});
btn_show.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
alert.show();
}
});
}
}
~~~
* * *
## 4.示例代碼下載
[AlertDialogDemo.zip](http://www.runoob.com/wp-content/uploads/2015/09/AlertDialogDemo.zip)
[AlertDialogDemo1.zip](http://www.runoob.com/wp-content/uploads/2015/09/AlertDialogDemo1.zip)
* * *
## 本節小結:
好的,本節給大家介紹了一下AlertDialog的基本使用,寫了幾個調用AlertDialog的例子, 最后還通過setView方法自定義了一下我們的AlertDialog!是不是還意猶未盡呢?但這說不上 真正的自定義控件,我們把自定義控件放到進階系列,到時后會有個專題來和大家探討 下自定義控件~敬請期待~就說這么多,謝謝~
- 第一章——環境搭建和開發相關
- 1.0 Android基礎入門教程
- 1.1 背景相關與系統架構分析
- 1.2 開發環境搭建
- 1.2.1 使用Eclipse + ADT + SDK開發Android APP
- 1.2.2 使用Android Studio開發Android APP
- 1.3 SDK更新不了問題解決
- 1.4 Genymotion模擬器安裝
- 1.5 GIT教程
- 1.5.1 Git使用教程之本地倉庫的基本操作
- 1.5.2 Git之使用GitHub搭建遠程倉庫
- 1.6 .9(九妹)圖片怎么玩
- 1.7 界面原型設計
- 1.8 工程相關解析(各種文件,資源訪問)
- 1.9 Android程序簽名打包
- 1.11 反編譯APK獲取代碼&資源
- 第二章——Android中的UI組件的詳解
- 2.1 View與ViewGroup的概念
- 2.2 布局
- 2.2.1 LinearLayout(線性布局)
- 2.2.2 RelativeLayout(相對布局)
- 2.2.3 TableLayout(表格布局)
- 2.2.4 FrameLayout(幀布局)
- 2.2.5 GridLayout(網格布局)
- 2.2.6 AbsoluteLayout(絕對布局)
- 2.3 表單
- 2.3.1 TextView(文本框)詳解
- 2.3.2 EditText(輸入框)詳解
- 2.3.3 Button(按鈕)與ImageButton(圖像按鈕)
- 2.3.4 ImageView(圖像視圖)
- 2.3.5.RadioButton(單選按鈕)&Checkbox(復選框)
- 2.3.6 開關按鈕ToggleButton和開關Switch
- 2.3.7 ProgressBar(進度條)
- 2.3.8 SeekBar(拖動條)
- 2.3.9 RatingBar(星級評分條)
- 2.4 控件
- 2.4.1 ScrollView(滾動條)
- 2.4.2 Date & Time組件(上)
- 2.4.3 Date & Time組件(下)
- 2.4.4 Adapter基礎講解
- 2.4.5 ListView簡單實用
- 2.4.6 BaseAdapter優化
- 2.4.7ListView的焦點問題
- 2.4.8 ListView之checkbox錯位問題解決
- 2.4.9 ListView的數據更新問題
- 2.5 Adapter類控件
- 2.5.0 構建一個可復用的自定義BaseAdapter
- 2.5.1 ListView Item多布局的實現
- 2.5.2 GridView(網格視圖)的基本使用
- 2.5.3 Spinner(列表選項框)的基本使用
- 2.5.4 AutoCompleteTextView(自動完成文本框)的基本使用
- 2.5.5 ExpandableListView(可折疊列表)的基本使用
- 2.5.6 ViewFlipper(翻轉視圖)的基本使用
- 2.5.7 Toast(吐司)的基本使用
- 2.5.8 Notification(狀態欄通知)詳解
- 2.5.9 AlertDialog(對話框)詳解
- 2.6 對話框控件
- 2.6.0 其他幾種常用對話框基本使用
- 2.6.1 PopupWindow(懸浮框)的基本使用
- 2.6.2 菜單(Menu)
- 2.6.3 ViewPager的簡單使用
- 2.6.4 DrawerLayout(官方側滑菜單)的簡單使用
- 第三章——Android的事件處理機制
- 3.1.1 基于監聽的事件處理機制
- 3.2 基于回調的事件處理機制
- 3.3 Handler消息傳遞機制淺析
- 3.4 TouchListener PK OnTouchEvent + 多點觸碰
- 3.5 監聽EditText的內容變化
- 3.6 響應系統設置的事件(Configuration類)
- 3.7 AnsyncTask異步任務
- 3.8 Gestures(手勢)
- 第四章——Android的四大組件
- 4.1.1 Activity初學乍練
- 4.1.2 Activity初窺門徑
- 4.1.3 Activity登堂入室
- 4.2.1 Service初涉
- 4.2.2 Service進階
- 4.2.3 Service精通
- 4.3.1 BroadcastReceiver牛刀小試
- 4.3.2 BroadcastReceiver庖丁解牛
- 4.4.1 ContentProvider初探
- 4.4.2 ContentProvider再探——Document Provider
- 4.5.1 Intent的基本使用
- 4.5.2 Intent之復雜數據的傳遞
- 第五章——Fragment(碎片)
- 5.1 Fragment基本概述
- 5.2.1 Fragment實例精講——底部導航欄的實現(方法1)
- 5.2.2 Fragment實例精講——底部導航欄的實現(方法2)
- 5.2.3 Fragment實例精講——底部導航欄的實現(方法3)
- 5.2.4 Fragment實例精講——底部導航欄+ViewPager滑動切換頁面
- 5.2.5 Fragment實例精講——新聞(購物)類App列表Fragment的簡單實現
- 第六章——Android數據存儲與訪問
- 6.1 數據存儲與訪問之——文件存儲讀寫
- 6.2 數據存儲與訪問之——SharedPreferences保存用戶偏好參數
- 6.3.1 數據存儲與訪問之——初見SQLite數據庫
- 6.3.2 數據存儲與訪問之——又見SQLite數據庫
- 第七章——Android網絡編程
- 7.1.1 Android網絡編程要學的東西與Http協議學習
- 7.1.2 Android Http請求頭與響應頭的學習
- 7.1.3 Android HTTP請求方式:HttpURLConnection
- 7.1.4 Android HTTP請求方式:HttpClient
- 7.2.1 Android XML數據解析
- 7.2.2 Android JSON數據解析
- 7.3.1 Android 文件上傳
- 7.3.2 Android 文件下載(1)
- 7.3.3 Android 文件下載(2)
- 7.4 Android 調用 WebService
- 7.5.1 WebView(網頁視圖)基本用法
- 7.5.2 WebView和JavaScrip交互基礎
- 7.5.3 Android 4.4后WebView的一些注意事項
- 7.5.4 WebView文件下載
- 7.5.5 WebView緩存問題
- 7.5.6 WebView處理網頁返回的錯誤碼信息
- 7.6.1 Socket學習網絡基礎準備
- 7.6.2 基于TCP協議的Socket通信(1)
- 7.6.3 基于TCP協議的Socket通信(2)
- 7.6.4 基于UDP協議的Socket通信
- 第八章——Android繪圖與動畫基礎
- 8.1.1 Android中的13種Drawable小結 Part 1
- 8.1.2 Android中的13種Drawable小結 Part 2
- 8.1.3 Android中的13種Drawable小結 Part 3
- 8.2.1 Bitmap(位圖)全解析 Part 1
- 8.2.2 Bitmap引起的OOM問題
- 8.3.1 三個繪圖工具類詳解
- 8.3.2 繪圖類實戰示例
- 8.3.3 Paint API之—— MaskFilter(面具)
- 8.3.4 Paint API之—— Xfermode與PorterDuff詳解(一)
- 8.3.5 Paint API之—— Xfermode與PorterDuff詳解(二)
- 8.3.6 Paint API之—— Xfermode與PorterDuff詳解(三)
- 8.3.7 Paint API之—— Xfermode與PorterDuff詳解(四)
- 8.3.8 Paint API之—— Xfermode與PorterDuff詳解(五)
- 8.3.9 Paint API之—— ColorFilter(顏色過濾器)(1/3)
- 8.3.10 Paint API之—— ColorFilter(顏色過濾器)(2-3)
- 8.3.11 Paint API之—— ColorFilter(顏色過濾器)(3-3)
- 8.3.12 Paint API之—— PathEffect(路徑效果)
- 8.3.13 Paint API之—— Shader(圖像渲染)
- 8.3.14 Paint幾個枚舉/常量值以及ShadowLayer陰影效果
- 8.3.15 Paint API之——Typeface(字型)
- 8.3.16 Canvas API詳解(Part 1)
- 8.3.17 Canvas API詳解(Part 2)剪切方法合集
- 8.3.18 Canvas API詳解(Part 3)Matrix和drawBitmapMash
- 8.4.1 Android動畫合集之幀動畫
- 8.4.2 Android動畫合集之補間動畫
- 8.4.3 Android動畫合集之屬性動畫-初見
- 8.4.4 Android動畫合集之屬性動畫-又見
- 第九章——Android中的多媒體開發
- 9.1 使用SoundPool播放音效(Duang~)
- 9.2 MediaPlayer播放音頻與視頻
- 9.3 使用Camera拍照
- 9.4 使用MediaRecord錄音
- 第十章——系統服務
- 10.1 TelephonyManager(電話管理器)
- 10.2 SmsManager(短信管理器)
- 10.3 AudioManager(音頻管理器)
- 10.4 Vibrator(振動器)
- 10.5 AlarmManager(鬧鐘服務)
- 10.6 PowerManager(電源服務)
- 10.7 WindowManager(窗口管理服務)
- 10.8 LayoutInflater(布局服務)
- 10.9 WallpaperManager(壁紙管理器)
- 10.10 傳感器專題(1)——相關介紹
- 10.11 傳感器專題(2)——方向傳感器
- 10.12 傳感器專題(3)——加速度/陀螺儀傳感器
- 10.12 傳感器專題(4)——其他傳感器了解
- 10.14 Android GPS初涉
- 第十一章——由來、答疑和資源
- 11.0《2015最新Android基礎入門教程》完結散花~