我之前主要是开发winform的,半路接手了公司的xamarin项目,新手,增加页面功能什么的没太大问题,但是对于安卓和苹果的平台实现没什么了解,在新项目开始后,决定重新整理框架,第一个问题就是安卓的启动页设置,没有启动页,app启动时会有一段时间的白屏。
首先看上个工程的启动页代码。程序的启动入口在哪里呢?按照C#的习惯,我找了SplashScreen的引用,没有任何引用,并且全局搜索,也没有搜到其他结果。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Content.PM;
namespace Saobag.Droid
{
[Activity(Label = "SaoBag", Icon = "@drawable/icon", Theme = "@style/Theme.Splash", MainLauncher = true, NoHistory = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class SplashScreen : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
DelayedNaviagition();
// Create your application here
}
private void DelayedNaviagition()
{
System.Threading.Tasks.Task.Delay(2000);
var intent = new Intent(this, typeof(MainActivity));
StartActivity(intent);
Finish();
}
}
}
那么,这个Activity和普通的类有什么不一样的地方呢,就是上面的这一行东西了:
[Activity(Label = "SaoBag", Icon = "@drawable/icon", Theme = "@style/Theme.Splash", MainLauncher = true, NoHistory = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]。
MainLauncher=true就是启动入口了。
NoHistory=true 的意思是从离开此activity 后,则注销,按返回键不会回到这里的。
Theme = "@style/Theme.Splash" 定义了activity 的主题,在resources/values/styles.xml 可以配置主题的内容,这里主要是一个背景图片,就是我们通常看到的app启动页的效果了。
<!--启动页-->
<style name="Theme.Splash" parent="MainTheme.Base">
<item name="android:windowBackground">@drawable/splash</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsTranslucent">false</item>
<item name="android:windowIsFloating">false</item>
<item name="android:backgroundDimEnabled">true</item>
</style>
这里我测试了一个假设:不需要启动页,也不想要白屏,是不是可以直接为MainActivity设置背景图片?
结果是启动效果可以,但是在后续app切换的时候会闪过背景图片,MainActivity有点像是一个主页。使用单独的启动页Activity,
启动后就直接将其关闭了,注意nohistory=true的作用。
总结:app的第一个activity需要一定的时间,如果不设定背景,则会显示白屏,那么设定一个有背景的Activity来进行缓冲就显的很重要了。