.NET Maui 8 Android横屏模式下Entry控件输入异常问题
问题
我用.NET Maui 8.0开发了一款面向Android设备的应用,遇到一个横屏模式下的异常问题:当焦点落在Entry控件上时,整个屏幕会变成空白,仅显示一个Done按钮,输入操作只能在屏幕右上角进行(并非屏幕上移,是完全空白状态)。点击Done按钮后屏幕恢复正常,输入的文本也能正确显示在Entry框中。竖屏模式下输入操作完全正常,请问能否实现原地输入,不让其他控件被隐藏?
对应的页面XAML代码如下:
<?xml version="1.0" encoding="utf-8" ?> <ContentPage x:Class="WmsClient.View.SettingsPasswordPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" Title="SettingsPasswordPage"> <Grid BackgroundColor="White" ColumnDefinitions="*" RowDefinitions="50,*,80,80"> <VerticalStackLayout Grid.Row="1"> <Label Margin="0,20,0,0" FontSize="26" HorizontalOptions="Center" Text="Password" TextColor="Black" /> <Frame Margin="0,20,0,0" Padding="0,0,0,0" BackgroundColor="White" BorderColor="Gray" CornerRadius="4" WidthRequest="300"> <Entry Grid.Row="1" FontSize="20" HorizontalOptions="Fill" IsEnabled="True" IsPassword="False" Text="{Binding EntryText}" TextColor="Black" /> </Frame> </VerticalStackLayout> </Grid> </ContentPage>
解决方案
以下是几种解决Android横屏模式下Entry输入时屏幕空白问题的可行方法:
1. 修改Android软键盘调整模式
在Android项目的AndroidManifest.xml中,给对应Activity添加软键盘行为配置,强制系统保留当前布局:
<activity android:name=".MainActivity" android:windowSoftInputMode="adjustPan">
adjustPan:系统会将整个界面向上平移,保证输入框可见,不会压缩或隐藏布局adjustResize:系统会调整界面大小以腾出软键盘空间,适合包含滚动控件的布局
2. 用ScrollView包裹布局
将当前的Grid放入ScrollView内部,这样软键盘弹出时,布局可通过滚动保持内容可见:
<ContentPage ...> <ScrollView> <Grid BackgroundColor="White" ColumnDefinitions="*" RowDefinitions="50,*,80,80"> <!-- 原有布局内容 --> </Grid> </ScrollView> </ContentPage>
3. 自定义Android Entry渲染器
通过自定义渲染器直接控制软键盘弹出时的窗口行为:
using Android.Content; using Android.Views.InputMethods; using Microsoft.Maui.Controls.Compatibility; using Microsoft.Maui.Controls.Compatibility.Platform.Android; [assembly: ExportRenderer(typeof(Entry), typeof(CustomEntryRenderer))] namespace YourAppNamespace.Platforms.Android { public class CustomEntryRenderer : EntryRenderer { public CustomEntryRenderer(Context context) : base(context) { } protected override void OnElementChanged(ElementChangedEventArgs<Entry> e) { base.OnElementChanged(e); if (Control != null) { var activity = Context as Android.App.Activity; activity.Window.SetSoftInputMode(SoftInput.AdjustPan); } } } }
4. 在MAUI配置中启用自定义渲染器
在MauiProgram.cs中注册自定义渲染器,确保配置生效:
builder.ConfigureMauiHandlers(handlers => { #if ANDROID handlers.AddHandler(typeof(Entry), typeof(YourAppNamespace.Platforms.Android.CustomEntryRenderer)); #endif });
内容的提问来源于stack exchange,提问作者phm
相关产品推荐
相关产品推荐

