Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 入門:AlertDialog 對話框的基本用法

編輯:關於 Android 程式設計

對話框是 Android 中最常見的互動元件之一,常用於確認刪除、提示選擇等操作。本文記錄 AlertDialog 的基本使用步驟,適合入門者參考。

使用 AlertDialog 大致分為四步:

1.取得 AlertDialog 的靜態內部類 Builder 物件,由它來建立對話框
2.透過 Builder 設定標題、按鈕以及按鈕的響應事件
3.呼叫 Builder 的 create() 方法建立對話框
4.呼叫 AlertDialog 的 show() 方法顯示對話框

版面配置 main.xml

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/MyTextView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:id="@+id/myButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="創建Alert對話框" /> </LinearLayout> 

MainActivity 程式碼

 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); myTextView = (TextView)findViewById(R.id.MyTextView); myButton = (Button)findViewById(R.id.myButton); //添加AlertDialog.Builder對象 final AlertDialog.Builder builder = new AlertDialog.Builder(this); //為activity中按鈕添加按鈕事件 myButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { builder.setTitle("您確定要刪除此條信息?"). //設置確定按鈕 setPositiveButton("Yes", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { myTextView.setText("刪除成功"); } }). //設置取消按鈕 setNegativeButton("No", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { myTextView.setText("取消刪除"); } }); //創建對話框 AlertDialog alertDialog = builder.create(); //顯示對話框 alertDialog.show(); } }); } } 

這段程式碼示範了最典型的「確認/取消」對話框:透過 setPositiveButton 與 setNegativeButton 分別設定兩顆按鈕及其點擊回呼,點擊後更新 TextView 的文字。掌握了 Builder 的串接寫法,就能輕鬆應付絕大多數對話框需求。

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