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

Blazor MAUI中聚焦条码扫描输入框时隐藏安卓虚拟键盘

问题描述

我使用Blazor MAUI开发安卓应用,采用MudBlazor作为UI库。在index.razor文件中使用了如下MudNumericField组件:

<MudNumericField @ref="PLUSearch"
Placeholder="PLU"
@bind-Value="barcodeString"
TextChanged="PLUchanged"
HideSpinButtons="true"
OnKeyDown="OnPLUKeyDown"
Immediate="true" />

我希望页面渲染后立即聚焦该输入框,目前已通过在OnInitializedAsync()方法中调用PLUSearch.FocusAsync()实现聚焦,但会自动弹出安卓虚拟键盘。由于该输入框用于条码扫描,无需弹出键盘,请问如何实现聚焦但不触发键盘弹出?

解决方案

方式一:调用安卓原生API强制隐藏键盘

在输入框聚焦完成后,直接调用安卓原生的输入法管理器隐藏虚拟键盘,步骤如下:

  1. 在组件中注入平台应用服务:
[Inject]
public IPlatformApplication PlatformApplication { get; set; }
  1. 把聚焦逻辑移到OnAfterRenderAsync(确保组件渲染完成),并添加隐藏键盘的代码:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        await PLUSearch.FocusAsync();
        if (DeviceInfo.Platform == DevicePlatform.Android)
        {
            var context = PlatformApplication.ApplicationContext;
            var inputMethodManager = context.GetSystemService(Context.InputMethodService) as InputMethodManager;
            var currentFocus = context.CurrentFocus;
            if (currentFocus != null)
            {
                inputMethodManager.HideSoftInputFromWindow(currentFocus.WindowToken, HideSoftInputFlags.None);
            }
        }
    }
}

方式二:自定义输入模板添加禁止键盘属性

通过自定义MudNumericField的输入模板,给原生输入控件添加inputmode="none"属性,告知安卓系统无需弹出虚拟键盘:

<MudNumericField @ref="PLUSearch"
Placeholder="PLU"
@bind-Value="barcodeString"
TextChanged="PLUchanged"
HideSpinButtons="true"
OnKeyDown="OnPLUKeyDown"
Immediate="true">
    <InputTemplate>
        <input type="text" 
               @bind="context.Value" 
               class="mud-input-root mud-input-slot"
               @onkeydown="OnPLUKeyDown"
               autocomplete="off"
               @attributes="context.InputAttributes"
               inputmode="none" />
    </InputTemplate>
</MudNumericField>

这个属性既能保持输入框的聚焦状态,又不会触发虚拟键盘弹出,完全适配条码扫描的场景。

内容的提问来源于stack exchange,提问作者Lasitha Lankajeewa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 08:26:09