我正在实现一个自定义键盘,我将键 0-9 和小数分隔符表示为 Button 对象。然后我有一个最后一个键,它是退格键,它被表示为一个 ImageButton。
当我处理点击事件时,我知道如果用户点击了一个按钮,他们正在向文本字段添加一个元素,如果他们点击了一个 ImageButton,他们正在从文本字段中删除最后一个元素。
由于键盘只有两种可能的按钮类型,我想用 when 块实现这个逻辑,而不使用 else 分支。可能吗?查看密封的课程文档,我认为这可能不是,只是要求确保。
我想做这样的事情:
sealed class KeyboardButton {
class Button
class ImageButton
}
fun handleKeyPress(button: View) {
when(button) {
is KeyboardButton.Button -> // append element to text
is KeyboardButton.ImageButton -> // remove last element from text
}
}