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

Android AlertDialog 示例一:警告對話框

編輯:關於 Android 開發

Android AlertDialog 示例一:警告對話框


在 Android 開發中,我們經常需要在界面上彈出對話框來詢問用戶或讓其選擇,這類功能稱為 Android Dialog,AlertDialog 採用建造者模式實現。下面模擬卸載應用時最常見的警告對話框,如下圖:

layout 布局界面代碼:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:text="卸載" android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="show" android:id="@+id/button" /> </LinearLayout>

Java 實現代碼:

public class AlertDialogDemo extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.alterdialog); } public void show(View v){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("卸載"); builder.setMessage("確定卸載嗎"); builder.setPositiveButton("確定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(AlertDialogDemo.this,"點擊了確定按鈕",Toast.LENGTH_SHORT).show(); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(AlertDialogDemo.this,"點擊了取消按鈕",Toast.LENGTH_SHORT).show(); } }); builder.setNeutralButton("等等看吧", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(AlertDialogDemo.this,"點擊了中立按鈕",Toast.LENGTH_SHORT).show(); } }); builder.show(); } }

本例展示了警告對話框的三種按鈕:setPositiveButton(正面/確定)、setNegativeButton(反面/取消)與 setNeutralButton(中立),每個按鈕都可綁定各自的點擊事件,最後調用 show() 顯示。

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