Xamarin.Forms:如何在指定ContentPage禁用android:Application.WindowSoftInputModeAdjust="Resize"
如何在单个ContentPage中覆盖全局的Android键盘Resize模式配置
当然可以实现。你只需要针对特定的ContentPage,在Android平台端单独修改它的WindowSoftInputMode,覆盖全局的AdjustResize设置。
实现步骤
1. 创建自定义ContentPage子类
先定义一个继承自ContentPage的子类,用来标记需要禁用Resize模式的页面:
public class NoResizeSoftInputPage : ContentPage { }
之后你需要禁用Resize模式的页面,就继承这个子类(而非默认的ContentPage)。
2. 在Android平台端设置软键盘模式
根据你使用的框架(.NET MAUI 或 Xamarin.Forms),选择对应的实现方式:
针对.NET MAUI
在Android平台项目中创建自定义Handler并注册:
using Microsoft.Maui.Platform; using Android.Views; // 在MauiProgram.cs的CreateMauiApp方法中注册Handler builder.ConfigureMauiHandlers(handlers => { #if ANDROID handlers.AddHandler<NoResizeSoftInputPage, NoResizeSoftInputPageHandler>(); #endif }); // 自定义Handler类(放在Android平台项目中) public class NoResizeSoftInputPageHandler : ContentPageHandler { protected override void ConnectHandler(MauiContentPage platformView) { base.ConnectHandler(platformView); // 将模式改为AdjustPan(键盘弹出时平移页面,不调整布局大小) platformView.Window.SetSoftInputMode(SoftInput.AdjustPan); } // 可选:页面销毁时恢复全局的Resize模式 protected override void DisconnectHandler(MauiContentPage platformView) { platformView.Window.SetSoftInputMode(SoftInput.AdjustResize); base.DisconnectHandler(platformView); } }
针对Xamarin.Forms
在Android平台项目中创建自定义渲染器:
using Xamarin.Forms.Platform.Android; using Android.Views; [assembly: ExportRenderer(typeof(NoResizeSoftInputPage), typeof(NoResizeSoftInputPageRenderer))] namespace YourAppNamespace.Droid.Renderers { public class NoResizeSoftInputPageRenderer : PageRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Page> e) { base.OnElementChanged(e); if (e.NewElement != null) { // 设置为AdjustPan模式,覆盖全局的Resize配置 Activity.Window.SetSoftInputMode(SoftInput.AdjustPan); } } // 可选:页面销毁时恢复全局模式 protected override void Dispose(bool disposing) { if (disposing) { Activity.Window.SetSoftInputMode(SoftInput.AdjustResize); } base.Dispose(disposing); } } }
可选的软键盘模式说明
SoftInput.AdjustPan:键盘弹出时会平移页面内容,避免输入框被遮挡,但不会调整布局的大小,适配你的需求SoftInput.AdjustNothing:键盘弹出时既不调整布局也不平移页面,可能会遮挡输入框,仅在不需要显示输入框上方内容时使用
内容的提问来源于stack exchange,提问作者Rajzer
相关产品推荐
相关产品推荐

