Skip to content

系统对话框

源:Android AlertDialog | iOS UIAlertController

系统对话框用于向用户显示提示、确认或选择。本文展示如何跨平台显示原生对话框。

标准代码块

kotlin
data class DialogConfig(
    val title: String,
    val message: String,
    val positiveButton: String = "确定",
    val negativeButton: String? = null,
    val onPositive: () -> Unit = {},
    val onNegative: () -> Unit = {}
)

expect fun showDialog(config: DialogConfig)
kotlin
import android.app.AlertDialog
import androidx.fragment.app.FragmentActivity

actual fun showDialog(config: DialogConfig) {
    // 需要传入 Activity 实例
}

fun showDialog(activity: FragmentActivity, config: DialogConfig) {
    val builder = AlertDialog.Builder(activity)
        .setTitle(config.title)
        .setMessage(config.message)
        .setPositiveButton(config.positiveButton) { _, _ ->
            config.onPositive()
        }
    
    config.negativeButton?.let { text ->
        builder.setNegativeButton(text) { _, _ ->
            config.onNegative()
        }
    }
    
    builder.show()
}
kotlin
import platform.UIKit.*

actual fun showDialog(config: DialogConfig) {
    val alert = UIAlertController.alertControllerWithTitle(
        title = config.title,
        message = config.message,
        preferredStyle = UIAlertControllerStyleAlert
    )
    
    val positiveAction = UIAlertAction.actionWithTitle(
        title = config.positiveButton,
        style = UIAlertActionStyleDefault
    ) { _ ->
        config.onPositive()
    }
    alert.addAction(positiveAction)
    
    config.negativeButton?.let { text ->
        val negativeAction = UIAlertAction.actionWithTitle(
            title = text,
            style = UIAlertActionStyleCancel
        ) { _ ->
            config.onNegative()
        }
        alert.addAction(negativeAction)
    }
    
    val rootVC = UIApplication.sharedApplication.keyWindow?.rootViewController
    rootVC?.presentViewController(alert, animated = true, completion = null)
}
kotlin
import javax.swing.JOptionPane

actual fun showDialog(config: DialogConfig) {
    val options = if (config.negativeButton != null) {
        arrayOf(config.positiveButton, config.negativeButton)
    } else {
        arrayOf(config.positiveButton)
    }
    
    val result = JOptionPane.showOptionDialog(
        null,
        config.message,
        config.title,
        JOptionPane.YES_NO_OPTION,
        JOptionPane.INFORMATION_MESSAGE,
        null,
        options,
        options[0]
    )
    
    when (result) {
        0 -> config.onPositive()
        1 -> config.onNegative()
    }
}