Xamarin Android启动页前置红色背景问题求助
Xamarin Android启动页移除初始红色背景方案
问题
按官方文档实现Xamarin Android启动页后,应用启动流程为:先显示红色背景 → 加载启动页图片 → 进入MainActivity,需移除第一步,直接显示启动页。
解决方案
1. 修正SplashActivity的OnCreate方法
原代码使用带PersistableBundle的重载且未正确初始化,导致主题背景加载延迟。修改为标准OnCreate重载,且不设置ContentView(依赖主题的windowBackground显示启动页):
[Activity(Theme = "@style/MainTheme.Splash", MainLauncher = true, NoHistory = true, ScreenOrientation = ScreenOrientation.Portrait) ] public class SplashActivity : AppCompatActivity { static readonly string TAG = "X:" + typeof(SplashActivity).Name; // 使用不带PersistableBundle的OnCreate重载 protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // 无需设置ContentView,启动页由主题windowBackground提供 } // ... 其他代码后续修改 }
2. 修复OnResume中重复启动跳转逻辑
原代码同时启动Task和直接调用SimulateStartup,会触发两次跳转,且导致启动流程紊乱。修改为仅异步执行一次:
protected override void OnResume() { base.OnResume(); // 异步执行启动逻辑,用弃元操作符避免编译器警告 _ = SimulateStartup(); } async Task SimulateStartup() // 改为返回Task,避免async void的潜在问题 { await Task.Delay(5000); // 模拟启动耗时操作 StartActivity(new Intent(Application.Context, typeof(MainActivity))); }
3. 调整启动页主题配置
原主题中android:windowActionBar="true"与父主题Theme.AppCompat.Light.NoActionBar冲突,会导致默认背景透出。修改主题属性,统一使用AppCompat兼容属性:
<style name="MainTheme.Splash" parent="Theme.AppCompat.Light.NoActionBar"> <item name="android:windowBackground">@drawable/splash_screen</item> <item name="android:windowNoTitle">true</item> <item name="android:windowFullscreen">true</item> <item name="android:windowContentOverlay">@null</item> <item name="windowActionBar">false</item> <!-- 使用AppCompat属性,不带android:前缀 --> <item name="windowNoTitle">true</item> </style>
4. 优化启动页图片布局
原代码去掉android:gravity会导致图片布局异常,且可能延迟显示。改为使用fill属性实现全屏填充,确保图片与背景色同时加载:
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android" android:opacity="opaque"> <item> <color android:color="@color/splash_background"/> </item> <item> <bitmap android:src="@drawable/splash_logo" android:tileMode="disabled" android:gravity="fill" /> <!-- 填充全屏,避免布局异常 --> </item> </layer-list>
额外检查
- 确认
splash_background颜色是否为你期望的启动页背景色,避免红色是该颜色本身设置错误 - 压缩
splash_logo图片资源,过大的图片会导致加载延迟,出现背景色先显示的情况
内容的提问来源于stack exchange,提问作者Stephan Miller
相关产品推荐
相关产品推荐

