Xamarin.Forms(V2.5) Entry在Android模拟器显示空白无功能求助
我之前在维护Xamarin.Forms老项目时碰到过几乎一模一样的问题,结合你给出的代码和症状来看,问题根源大概率出在Android布局引擎对叠加控件的可见性切换处理上——毕竟Xamarin.Forms 2.5版本确实存在不少Android端的渲染bug。下面是几个亲测有效的解决方案,你可以逐个尝试:
方法1:合并叠加的Frame,用单个容器包裹切换的Entry
你当前在同一个Grid单元格里放了两个独立的Frame,Android的布局系统在切换它们的IsVisible时,经常会出现重绘不及时或者控件层级错乱的情况。建议把两个Entry放到同一个Frame中,用StackLayout或ContentView来控制各自的可见性,减少叠加的容器数量:
<Grid x:Name="InnerGridSparrateSwitch" Grid.Row="3" Grid.Column="1" IsVisible="{Binding IsFH}" HorizontalOptions="Fill"> <Grid.RowDefinitions> <RowDefinition Height="1*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="1*"/> <ColumnDefinition Width="1.5*"/> </Grid.ColumnDefinitions> <Button Text="{Binding Spareingabe}" Style="{StaticResource OnPlatformButton}" Command="{Binding SwitchSpareingabe}" Grid.Row="0" Grid.Column="0" FontAttributes="Bold" BackgroundColor="{DynamicResource AccentColor}"/> <!-- 合并为单个Frame --> <Frame Style="{StaticResource RunderRahmen}" Grid.Row="0" Grid.Column="1"> <StackLayout> <Entry x:Name="Eingabe_FHRate" IsVisible="{Binding EingabeSparRate}" Style="{StaticResource Eingabefeld_small}" Text="{Binding SparrateView, Mode=TwoWay}" IsEnabled="{Binding AutoCalcActive, Converter={StaticResource IsBusyConverter}}"/> <Entry x:Name="Eingabe_SparProzent" IsVisible="{Binding EingabeSparRate, Converter={StaticResource IsBusyConverter}}" Style="{StaticResource Eingabefeld_small}" Text="{Binding TilgungssatzView, Mode=TwoWay}"/> </StackLayout> </Frame> </Grid>
这种修改最小,能直接避免Android对叠加Frame的渲染异常,我之前用这个方法解决过类似的空白问题。
方法2:手动触发布局重绘
如果不想修改布局结构,可以在切换命令执行完成后,强制让Grid重新计算布局。通过ForceLayout()方法触发Android的重绘逻辑:
首先在ViewModel的SwitchSpareingabe命令末尾添加布局刷新逻辑:
public ICommand SwitchSpareingabe => new Command(() => { // 你的原有切换逻辑 EingabeSparRate = !EingabeSparRate; // 主线程触发布局重绘 Device.BeginInvokeOnMainThread(() => { MessagingCenter.Send(this, "RefreshInnerGrids"); }); });
然后在页面的代码后台订阅这个消息,强制刷新目标Grid:
public YourPage() { InitializeComponent(); MessagingCenter.Subscribe<YourViewModel>(this, "RefreshInnerGrids", (vm) => { Device.BeginInvokeOnMainThread(() => { InnerGridSparrateSwitch.ForceLayout(); InnerGridTilgungsrateSwitch.ForceLayout(); }); }); }
这样能确保Android在可见性切换后,重新渲染Entry控件。
方法3:升级Xamarin.Forms版本(如果项目允许)
Xamarin.Forms 2.5是2018年的老版本,后续的3.x、4.x版本修复了大量Android端的布局渲染bug。如果你的项目没有强依赖旧版本的特性,升级到较新的稳定版本(比如4.8或5.x),大概率能直接解决这个问题。不过升级前记得做好代码备份和兼容性测试。
方法4:排查Frame的Style冲突
你的RunderRahmen样式中如果包含Padding、IsClippedToBounds或者自定义的Renderer相关设置,可能会在Android上和Entry的布局产生冲突。可以临时注释掉Style="{StaticResource RunderRahmen}",测试Entry是否能正常显示,逐步排查样式中的问题。
内容的提问来源于stack exchange,提问作者Marco

