首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

MIDP 高級 UI 組件深度解析(四):Alert 警告框完整指南

     編輯:Java 相關知識

javax.microedition.lcdui.Alert 是 MIDP 高級 UI 中用於短暫信息提示、錯誤警告、確認對話框的特殊 Screen 子類。它具有自動播放提示音、自動超時返回、可選進度指示器等獨特行為。本文系統梳理 Alert 類型、屬性、生命周期、最佳實踐,並提供完整可運行示例。

Alert 核心特性

特性說明
繼承體系Screen → Displayable (可添加 Command、Ticker、CommandListener)
顯示機制Display.setCurrent(alert) → 播放類型聲音 → 顯示內容 → 超時/用戶操作 → 自動返回前一 Screen
前置條件**必須**在顯示 Alert 前設置好返回目標 Screen,否則拋出 IllegalStateException
模態性阻塞用戶交互,直到超時或用戶按鍵響應

五大預定義類型 (AlertType)

AlertType 為不可實例化的工具類,提供 5 種標準類型,對應不同聲音與默認圖標:

類型常量語義典型場景默認聲音
ALARM警報鬧鐘、緊急通知響亮重複
CONFIRMATION確認操作成功、需用戶確認輕快肯定
ERROR錯誤異常、操作失敗刺耳警告
INFO信息一般提示、幫助信息柔和提示
WARNING警告潛在風險、權限請求注意提示

關鍵 API 詳解


Alert alert = new Alert("標題"); // 或 new Alert("標題", "內容", null, AlertType.INFO)

// 核心設置
alert.setType(AlertType.ERROR);                    // 類型 (影響聲音/圖標)
alert.setString("詳細信息文本...");                // 主文本 (支持換行 \n)
alert.setImage(Image.createImage("/icon.png"));    // 自定義圖標 (可選)
alert.setTimeout(3000);                            // 顯示毫秒數 (默認設備相關)
alert.setTimeout(Alert.FOREVER);                   // 永不超時,需用戶按鍵關閉

// 進度指示器 (超時倒計時視覺化)
Gauge gauge = new Gauge(null, false, 10, 0);       // 最大值 10,初始 0
alert.setIndicator(gauge);                         // 關聯指示器

// 獲取器
AlertType type = alert.getType();
String text = alert.getString();
Image img = alert.getImage();
int timeout = alert.getTimeout();
Gauge indicator = alert.getIndicator();

完整示例:類型/超時/指示器動態配置


import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class AlertDemoMIDlet extends MIDlet implements CommandListener {
    private Display display;
    private Form configForm;
    private ChoiceGroup typeChoice, timeoutChoice, optionChoice;
    private static final Command CMD_SHOW = new Command("顯示", Command.OK, 1);
    private static final Command CMD_EXIT = new Command("退出", Command.EXIT, 2);

    private static final String[] TYPES = {"ALARM", "CONFIRMATION", "ERROR", "INFO", "WARNING"};
    private static final AlertType[] TYPE_VALUES = {
        AlertType.ALARM, AlertType.CONFIRMATION, AlertType.ERROR, AlertType.INFO, AlertType.WARNING
    };
    private static final String[] TIMEOUTS = {"2秒", "5秒", "10秒", "永久 (FOREVER)"};
    private static final int[] TIMEOUT_VALUES = {2000, 5000, 10000, Alert.FOREVER};

    protected void startApp() {
        if (display == null) display = Display.getDisplay(this);
        if (configForm == null) buildConfigForm();
        display.setCurrent(configForm);
    }

    private void buildConfigForm() {
        configForm = new Form("Alert 配置");
        typeChoice = new ChoiceGroup("類型", Choice.POPUP, TYPES, null);
        timeoutChoice = new ChoiceGroup("超時", Choice.POPUP, TIMEOUTS, null);
        optionChoice = new ChoiceGroup("選項", Choice.MULTIPLE, new String[]{"顯示進度指示器"}, null);
        configForm.append(typeChoice);
        configForm.append(timeoutChoice);
        configForm.append(optionChoice);
        configForm.addCommand(CMD_SHOW);
        configForm.addCommand(CMD_EXIT);
        configForm.setCommandListener(this);
    }

    public void commandAction(Command c, Displayable d) {
        if (c == CMD_EXIT) { notifyDestroyed(); return; }
        if (c != CMD_SHOW) return;

        int typeIdx = typeChoice.getSelectedIndex();
        int timeoutIdx = timeoutChoice.getSelectedIndex();
        boolean showIndicator = optionChoice.isSelected(0);

        Alert alert = new Alert("演示 Alert");
        alert.setType(TYPE_VALUES[typeIdx]);
        alert.setTimeout(TIMEOUT_VALUES[timeoutIdx]);
        alert.setString(TYPES[typeIdx] + " 類型\n超時: " + TIMEOUTS[timeoutIdx]);

        if (showIndicator) {
            Gauge indicator = createIndicator(TIMEOUT_VALUES[timeoutIdx]);
            alert.setIndicator(indicator);
        }

        // 關鍵:設置返回目標 (當前配置表單)
        display.setCurrent(alert, configForm);
    }

    private Gauge createIndicator(int timeout) {
        if (timeout == Alert.FOREVER) {
            // 無限進度條 (動畫)
            return new Gauge(null, false, Gauge.INDEFINITE, Gauge.CONTINUOUS_RUNNING);
        }
        // 定時進度條:最大值 = 秒數,啟動線程每秒更新
        final int seconds = timeout / 1000;
        final Gauge gauge = new Gauge(null, false, seconds, 0);
        new Thread(() -> {
            for (int i = 0; i < seconds; i++) {
                gauge.setValue(i);
                try { Thread.sleep(1000); } catch (InterruptedException ignored) {}
            }
        }).start();
        return gauge;
    }

    protected void pauseApp() {}
    protected void destroyApp(boolean unconditional) {}
}

Alert 生命周期與行為細節

  1. setCurrent(alert, nextScreen):顯示 Alert,超時/關閉後自動切換到 nextScreen
  2. 播放類型對應聲音 (設備相關,可靜音模式下無聲)
  3. 若 timeout > 0:倒計時結束自動關閉,返回 nextScreen
  4. 若 timeout == FOREVER:一直顯示,直到用戶按鍵 (通常是軟鍵「確定」/「返回」)
  5. 若 Alert 有 Command 且超時:超時會自動激活該 Command (僅當只有一個 Command 時)
  6. 用戶按鍵關閉:觸發 CommandListener (若有 Command),然後返回 nextScreen

最佳實踐與避坑指南

場景建議錯誤示範
網絡請求失敗提示ERROR 類型 + 3-5 秒超時 + 關鍵錯誤碼FOREVER 導致用戶卡死,無法返回重試
表單提交成功確認CONFIRMATION + 2 秒 + 自動返回列表需用戶手動關閉,增加操作步驟
關鍵權限請求WARNING + FOREVER + 兩個 Command (允許/拒絕)無 Command 用戶無法響應
長時間後台任務進度INFO + FOREVER + Gauge.INDEFINITE + 取消 Command無進度指示用戶以為死機
文本過長簡潔核心信息,詳細放入後續 Form塞入大段文本,小屏幕截斷/換行混亂
圖標加載失敗try-catch 包裹 createImage,失敗設 null拋出異常導致 Alert 無法顯示

總結

Alert 是 MIDP 中唯一自帶聲音、自動超時返回、內置進度指示器的高級組件。掌握類型選擇、超時策略、返回目標設置、指示器配置四大要素,即可構建良好的用戶交互反饋體驗。記住鐵律:顯示 Alert 前必須確定返回 Screen,否則運行時崩潰。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved