.NET8 MAUI ListView选中项背景橙色问题及解决尝试求助
解决.NET 8 MAUI Android ListView选中项橙色背景问题
问题回顾
此前咨询过该问题,得到答复称是Bug会在.NET 8版本修复,但升级后问题仍存在:Android设备上运行.NET 8 MAUI应用时,ListView显示正常,但点击选中项背景变为橙色。尝试添加style.xml并修改MainActivity.cs主题设置后无效,且OnCellPropertyChanged仅从下一页返回时才触发。
可行解决方案
方案1:使用VisualStateManager自定义选中状态(跨平台)
直接在XAML的ViewCell中定义选中状态样式,无需依赖Android原生配置,适配性更强:
<ListView ItemsSource="{Binding Items}"> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <VisualStateManager.VisualStateGroups> <VisualStateGroup Name="CommonStates"> <VisualState Name="Normal"> <VisualState.Setters> <Setter Property="BackgroundColor" Value="Transparent" /> </VisualState.Setters> </VisualState> <VisualState Name="Selected"> <VisualState.Setters> <Setter Property="BackgroundColor" Value="#YourDesiredColor" /> </VisualState.Setters> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <!-- 你的Cell内容 --> <Label Text="{Binding Text}" /> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView>
方案2:修改Android原生主题的正确属性
之前使用的android:colorActivatedHighlight在部分Android版本中已失效,改用android:listSelector或自定义drawable:
- 在
Resources/drawable下创建list_selector.xml:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@android:color/transparent" /> <item android:state_selected="true" android:drawable="@android:color/transparent" /> <item android:drawable="@android:color/transparent" /> </selector>
- 修改
style.xml,确保主题继承自Maui.MainTheme而非启动页主题:
<?xml version="1.0" encoding="utf-8"?> <resources> <style name="Test.MainTheme" parent="Maui.MainTheme"> <item name="android:listSelector">@drawable/list_selector</item> </style> </resources>
- 保持
MainActivity.cs的主题配置不变。
方案3:自定义Android ListView渲染器
如果上述方法无效,可通过自定义渲染器直接修改原生ListView的选中样式:
using Android.Content; using Android.Widget; using Microsoft.Maui.Controls.Platform; [assembly: ExportRenderer(typeof(ListView), typeof(CustomListViewRenderer))] namespace YourAppName.Platforms.Android { public class CustomListViewRenderer : ListViewRenderer { public CustomListViewRenderer(Context context) : base(context) { } protected override void OnElementChanged(ElementChangedEventArgs<ListView> e) { base.OnElementChanged(e); if (Control != null) { Control.SetSelector(Android.Resource.Color.Transparent); // 或者设置自定义drawable // Control.SetSelector(Resource.Drawable.list_selector); } } } }
内容的提问来源于stack exchange,提问作者Enrico
相关产品推荐
相关产品推荐

