Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 技術基礎

2.5.9 AlertDialog 對話框完整指南

編輯:Android 技術基礎

前言

本節要介紹的是顯示提示資訊的第三個元件 AlertDialog(對話框),同時它也是其他 Dialog 的父類,例如 ProgressDialog、TimePickerDialog 等;而 AlertDialog 自己的父類是 Dialog。

有別於前面學過的 Toast 與 Notification,AlertDialog 不能直接 new 出來——翻開原始碼會發現它的建構子是 protected 的。要建立 AlertDialog,得使用該類中的靜態內部類 Builder,透過它呼叫 AlertDialog 的相關方法完成客製,最後調用 show() 把對話框顯示出來。下面我們從基本用法一路走到自訂版面。官方文件:AlertDialog


一、基本使用流程

  • Step 1:建立 AlertDialog.Builder 物件;
  • Step 2:呼叫 setIcon() 設定圖示,setTitle() 或 setCustomTitle() 設定標題;
  • Step 3:設定對話框內容,可用 setMessage() 或其他方法指定顯示的內容;
  • Step 4:呼叫 setPositiveButton / setNegativeButton / setNeutralButton 設定確定、取消、中立三種按鈕;
  • Step 5:呼叫 create() 產生物件,再呼叫 show() 顯示對話框。

二、幾種常見對話框的實作

執行結果:

核心程式碼:

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() 顯示。另外,你可能注意到點擊對話框外部區域時它會消失,若不想這樣,為 builder 加上 setCancelable(false) 即可。


三、用 Builder 的 setView() 自訂版面

我們可以自己寫一個不同於系統預設的版面,再透過 setView() 把它載入 AlertDialog。下面來實作看看。

執行結果:

關鍵程式碼

先準備兩組按鈕用的 selector:

btn_selector_exit.xml:

 <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="https://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_selector_choose.xml:

 <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="https://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="https://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:text /> <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("https://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(); } }); } } 

四、範例程式碼下載

AlertDialogDemo.zip

AlertDialogDemo1.zip


小結

本節把 AlertDialog 的基本用法與幾種常見形態走了一遍,最後還透過 setView 自訂了版面。嚴格來說這還算不上真正的自訂元件,那部分我們放到進階系列,屆時會有專題來深入探討。敬請期待。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved