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

Android 基礎元件實戰(一):通知、對話框與進度條的完整範例

編輯:關於 Android 程式設計

本文用一個小範例把幾個最常見的 UI 元件串起來:狀態列通知、各種類型的 AlertDialog,以及 ProgressDialog 進度對話框。

小技巧:按鈕之間若要切換事件處理方式,只要在 XML 中加上 android:onClick="clearNoti" 並實作同名方法即可,不必撰寫 setOnClickListener。

一、發出狀態列通知

public void Notification(View v) {
    showNotification("親來短信了", "5557", "我喜歡你",
            R.drawable.ic_launcher, R.drawable.ic_launcher);
}

public void showNotification(String tickerText, String contentTitle,
                             String contentText, int iconId, int notiId) {
    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    // 建立一個 Notification
    Notification notification = new Notification();
    notification.icon = iconId;                       // 通知圖示
    notification.tickerText = tickerText;             // 短暫飄出的文字
    notification.when = System.currentTimeMillis();    // 通知時間
    notification.defaults = Notification.DEFAULT_VIBRATE;  // 震動效果
    // 建立 PendingIntent,交由 Android 系統維護
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, getIntent(), 0);
    // 設定詳細內容
    notification.setLatestEventInfo(this, contentTitle, contentText, pendingIntent);
    // 以 notiId 作為識別碼發出通知
    notificationManager.notify(notiId, notification);
}

二、清除通知

public void clearNoti(View v) {
    notificationManager.cancelAll();   // 清除所有通知
}

三、基本對話框

public void DiaLog() {
    AlertDialog alertDialog = new AlertDialog.Builder(this)
        .setIcon(R.drawable.mw)
        .setTitle("DiaLog")
        .setMessage("是否創建文件")
        .setPositiveButton("確認", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                new AlertDialog.Builder(MainActivity.this)
                    .setMessage("您點擊了確認按鈕,文件已經被創建").show();
            }
        })
        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                new AlertDialog.Builder(MainActivity.this)
                    .setMessage("您已經選擇了取消的按鈕,該文件不會被創建")
                    .create().show();
            }
        }).show();
}

四、簡單列表對話框

public void Simplelistdialog(View v) {
    final String items[] = {"java", "php", "3g", ".net"};
    AlertDialog alertDialog = new AlertDialog.Builder(this)
        .setTitle("簡單列表對話框")
        .setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getApplicationContext(),
                        "親,你喜歡的科目是:" + items[which],
                        Toast.LENGTH_LONG).show();
            }
        }).show();
}

五、單選列表對話框

setSingleChoiceItems 有三種多載形式:傳入字串陣列、傳入資源 ID 陣列,或傳入 Cursor(此時需指定 labelColumn,也就是資料集中作為顯示文字的那個欄位名稱)。第二個參數 checkedItem 用來指定預設勾選項。

public void Radiolistdialog(View v) {
    final String items[] = {"java", "php", "3g", ".net"};
    AlertDialog alertDialog = new AlertDialog.Builder(this)
        .setTitle("單選列表對話框")
        .setSingleChoiceItems(items, 1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getApplicationContext(),
                        "親,你喜歡的科目是:" + items[which],
                        Toast.LENGTH_LONG).show();
            }
        }).show();
}

六、多選列表對話框

public void Multiselectlistdialog(View v) {
    final String items[] = {"Java", "PHP", "3G", ".NET"};
    new AlertDialog.Builder(this)
        .setTitle("多選列表對話框")
        .setMultiChoiceItems(items, new boolean[]{false, true, true, false},
            new DialogInterface.OnMultiChoiceClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                    if (isChecked) {
                        Toast.makeText(getApplicationContext(),
                                "親,你選中的科目是:" + items[which],
                                Toast.LENGTH_LONG).show();
                    }
                }
            })
        .setPositiveButton("確認", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getApplicationContext(),
                        "親,你喜歡的科目有:", Toast.LENGTH_LONG).show();
            }
        }).show();
}

七、進度條對話框

ProgressDialog 搭配 Handler 定時送訊息,就能做出前進的進度條;setProgressStyle 可選擇 STYLE_SPINNER(旋轉)或 STYLE_HORIZONTAL(水平)。

public void ProgressDialog(View v) {
    handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case PRO:
                    if (PRO >= MAX_PROGRESS) {
                        progress = 0;
                        progressDialog.dismiss();     // 銷毀對話框
                    } else {
                        progress++;
                        progressDialog.incrementProgressBy(1);
                        handler.sendEmptyMessageDelayed(PRO, 100);  // 延遲發送
                    }
                    break;
                default:
                    break;
            }
        }
    };
    progressDialog = new ProgressDialog(this);
    progressDialog.setIcon(R.drawable.mw);
    progressDialog.setTitle("正在處理數據......");
    progressDialog.setMessage("請稍後.....");
    progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    progressDialog.setMax(MAX_PROGRESS);
    progressDialog.setButton("暫停", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            handler.removeMessages(PRO);
        }
    });
    progressDialog.setButton2("取消", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            handler.removeMessages(PRO);   // 清空訊息佇列
            progress = 0;
            progressDialog.setProgress(progress);
        }
    });
    progressDialog.show();
    // 必須在 show 之後設定,show 之前可能出問題
    progress = (progress > 0) ? progress : 0;
    progressDialog.setProgress(progress);
    handler.sendEmptyMessage(PRO);
}

另一種常見的呈現方式如下:

八、自訂版面配置對話框

想讓對話框呈現自訂的內容,只要用 LayoutInflater 把配置檔轉成 View,再交給 setView() 即可。

public void MyDialog(View v) {
    LayoutInflater layoutInflater = getLayoutInflater();
    View view = layoutInflater.inflate(R.layout.activity_main, null);
    new AlertDialog.Builder(this)
        .setView(view)
        .setTitle("自定義的對話框")
        .setPositiveButton("確認按鈕", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 在這裡處理確認後的邏輯
            }
        }).show();
}

版本提醒

本範例中的 Notification 寫法、setLatestEventInfo() 與 ProgressDialog 都屬於早期 API。在 Android 5.0 之後,通知應改用 NotificationCompat.Builder 搭配 NotificationChannel(Android 8.0 起強制要求),ProgressDialog 也已被官方標示為不建議使用,正式專案中請改用 ProgressBar 或 SwipeRefreshLayout 呈現等待狀態。

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