native.showAlert()

类型 函数
native.*
返回值 对象
修订 版本 2024.3703
关键词 alert, native alert, alert popup(警报,原生警报,警报弹窗)
另请参阅 native.cancelAlert()

概述

使用原生警报控件显示一个带有一个或多个按钮的弹出警报框。程序活动(包括动画)将在后台继续,但所有其他用户交互都将被阻止,直到用户选择一个按钮或取消对话框。

注意事项

语法

native.showAlert( title, message [, buttonLabels [, listener] ] )
title (必填)

字符串. 警报中显示的标题字符串。

message (必填)

字符串. 警报文本中显示的消息字符串。

buttonLabels (可选)

. 字符串表,每个字符串都将创建一个带有相应标签的按钮。至少包含一个 buttonLabel,否则对话框将没有任何按钮。警报框中最多可以有五个按钮。最常见的格式是一个或两个按钮,例如 "确定""取消"

listener (可选)

侦听器. 当用户按下警报框中的任何按钮时要调用的侦听器函数。它可以根据按钮的数字索引为每个按钮分配一个操作:第一个按钮的索引为 1,第二个按钮的索引为 2,依此类推。侦听器可以是函数侦听器或表侦听器,并且分派给侦听器的事件将具有以下附加属性

  • event.action 表示警报是如何被关闭的:"cancelled" 表示调用了 native.cancelAlert() 来关闭警报,而 "clicked" 表示用户单击了按钮来关闭警报。
  • event.index 是所按下按钮的索引。它对应于 buttonLabels 参数中的索引。

示例

-- Handler that gets notified when the alert closes
local function onComplete( event )
    if ( event.action == "clicked" ) then
        local i = event.index
        if ( i == 1 ) then
            -- Do nothing; dialog will simply dismiss
        elseif ( i == 2 ) then
            -- Open URL if "Learn More" (second button) was clicked
            system.openURL( "https://solar2d.com/" )
        end
    end
end
 
-- Show alert with two buttons
local alert = native.showAlert( "Solar2D", "Dream. Build. Ship.", { "OK", "Learn More" }, onComplete )