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

Xamarin.Forms:键盘及加载弹窗后恢复沉浸式粘性模式问询

解决Xamarin.Forms Android沉浸式粘性模式失效的问题

这个问题我之前也踩过坑——Android系统在键盘弹出、Dialog显示时会强制退出沉浸式模式,而ImmersiveSticky并不能自动帮我们恢复状态。下面给你几个实用的方案,组合起来就能完美解决你的问题:

1. 监听键盘隐藏事件,自动恢复沉浸式

当键盘收起时,我们可以通过监听布局变化来判断状态,然后重新调用你的SetFullscreen()方法:

protected override void OnCreate(Bundle bundle) {
    TabLayoutResource = Resource.Layout.Tabbar;
    ToolbarResource = Resource.Layout.Toolbar;
    base.OnCreate(bundle);
    Xamarin.Forms.Forms.Init(this, bundle);
    SetFullscreen();
    LoadApplication(new App());

    // 添加键盘状态监听逻辑
    SetupKeyboardVisibilityListener();
}

void SetupKeyboardVisibilityListener() {
    var rootView = Window.DecorView.RootView;
    rootView.ViewTreeObserver.GlobalLayout += (sender, e) => {
        Rect visibleFrame = new Rect();
        rootView.GetWindowVisibleDisplayFrame(visibleFrame);
        int screenHeight = rootView.RootView.Height;
        // 当键盘高度小于屏幕15%时,判断为键盘已隐藏
        int keyboardHeight = screenHeight - visibleFrame.Bottom;

        if (keyboardHeight < screenHeight * 0.15) {
            // 必须回到UI线程执行沉浸式设置
            RunOnUiThread(SetFullscreen);
        }
    };
}

2. 监听Acr.UserDialogs的Loading关闭事件

ShowLoading()弹出的Dialog会触发系统栏显示,所以我们要在HideLoading()时主动恢复沉浸式:

protected override void OnCreate(Bundle bundle) {
    // ... 其他初始化代码 ...

    // 订阅Loading弹窗的隐藏事件
    Acr.UserDialogs.UserDialogs.Instance.HideLoading += (sender, args) => {
        // 延迟100ms执行,确保弹窗完全关闭后再恢复
        Task.Delay(100).ContinueWith(_ => {
            RunOnUiThread(SetFullscreen);
        });
    };
}

3. 全局焦点恢复时强制兜底

不管是页面切换、Dialog关闭还是其他场景导致窗口重新获得焦点,都强制恢复沉浸式状态:

public override void OnWindowFocusChanged(bool hasFocus) {
    base.OnWindowFocusChanged(hasFocus);
    if (hasFocus) {
        SetFullscreen();
    }
}

protected override void OnResume() {
    base.OnResume();
    SetFullscreen();
}

为什么这些方法有效?

Android系统在弹出键盘、Dialog这类系统级组件时,会自动重置SystemUiVisibility,而ImmersiveSticky只有在用户主动滑动状态栏时才会临时显示后自动隐藏,系统触发的状态变化不会自动恢复。通过监听键盘状态、UserDialogs事件,再加上焦点和页面生命周期的兜底逻辑,就能覆盖所有导致沉浸式失效的场景。

把这些代码整合到你的MainActivity.cs里,就能实现始终保持沉浸式模式的效果了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:38:27