You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Godot 4中始终保持虚拟键盘显示?解决LineEdit切换开合问题

解决Godot 4移动设备上LineEdit切换时虚拟键盘反复开合的问题

要让虚拟键盘在切换LineEdit时保持打开状态,你可以通过手动控制键盘显示状态、拦截默认焦点切换的键盘行为来实现,以下是具体方案:

方案一:全局监听焦点变化,手动维持键盘状态

这个方法通过全局脚本跟踪LineEdit的焦点切换,仅在用户真正离开所有输入框时才关闭键盘:

  1. 给所有LineEdit分组:在场景编辑器中,选中所有LineEdit控件,添加到名为line_edits的组中(右键控件 → 分组 → 添加到新组)。

  2. 添加全局控制脚本:在场景的根Control节点上附加以下脚本:

extends Control

var _current_focused: LineEdit = null

func _ready():
    # 遍历组内所有LineEdit,连接焦点信号
    for node in get_tree().get_nodes_in_group("line_edits"):
        if node is LineEdit:
            node.focus_entered.connect(_on_focus_entered)
            node.focus_exited.connect(_on_focus_exited)

func _on_focus_entered(line_edit: LineEdit):
    _current_focused = line_edit
    # 强制显示虚拟键盘,确保切换时键盘不关闭
    DisplayServer.show_virtual_keyboard()

func _on_focus_exited(line_edit: LineEdit):
    # 延迟一帧检查新焦点,避免切换时误关闭键盘
    call_deferred("_verify_new_focus")

func _verify_new_focus():
    new_focus = get_tree().get_focus_owner()
    # 只有当新焦点不是LineEdit时,才关闭键盘
    if not (new_focus is LineEdit):
        DisplayServer.hide_virtual_keyboard()
        _current_focused = null

方案二:自定义LineEdit类,禁用默认键盘关闭行为

如果不想用全局脚本,也可以自定义LineEdit,重写焦点通知来阻止默认的键盘关闭逻辑:

extends LineEdit

func _notification(what: int):
    # 拦截焦点退出的默认通知,避免触发键盘关闭
    if what == NOTIFICATION_FOCUS_EXIT:
        # 仅执行自定义逻辑,不调用父类的默认处理
        return
    # 其他通知正常交给父类处理
    super._notification(what)

然后将场景中的所有LineEdit替换为这个自定义类,再结合全局的焦点监听确保切换时键盘保持打开(和方案一的_on_focus_entered逻辑配合)。

注意事项

  • 测试时需确保移动设备的系统设置允许应用显示虚拟键盘,且Godot导出设置中启用了输入相关权限。
  • 部分Android/iOS版本可能存在系统级的键盘行为差异,建议在目标设备上测试调整延迟时间或逻辑。

内容的提问来源于stack exchange,提问作者Luka Shergelashvili

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 07:53:25