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

Android 開發入門:AlertDialog 對話框使用總結

編輯:關於 Android 程式設計

提示訊息對開發者來說想必不陌生——使用者點擊某個按鈕後,App 給出一個回饋,這就是提示訊息的功能。良好的提示能顯著提升使用者體驗,因此本篇就來把 AlertDialog 的用法整理清楚。

先看一個完整的範例:

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class DialogDemoActivity extends Activity {
    private Button button;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog);
        button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                AlertDialog.Builder builder = new AlertDialog.Builder(DialogDemoActivity.this);
                builder.setTitle("Message")
                    .setMessage("你確定要上網麼?")
                    .setCancelable(false)
                    .setPositiveButton("確定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {
                            Intent intent = new Intent(
                                    Intent.ACTION_VIEW, Uri.parse("https://www.haosou.com"));
                            startActivity(intent);
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });
                AlertDialog dialog = builder.create();
                dialog.show();
            }
        });
    }
}

以上程式碼就能實現基本的提示視窗。接著我們把每個方法逐一拆解。

首先建立 Builder 物件,所有參數配置都靠它完成:

AlertDialog.Builder builder = new AlertDialog.Builder(XxxActivity.this);

常用的方法有以下幾個:

設定標題:

builder.setTitle("Message");

設定提示內容:

builder.setMessage("你確定要上網麼?");

設定返回鍵是否生效,傳入 false 後返回鍵失效,傳入 true 則生效:

builder.setCancelable(false);

新增「確定」按鈕並綁定事件:

builder.setPositiveButton("確定", 事件);

新增「取消」按鈕並綁定事件:

builder.setNegativeButton("取消", 事件);

靈活搭配以上方法,就能做出各種提示視窗。不過預設樣式比較樸素,如果想要更精美的視覺效果,就需要進一步自訂樣式了。

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