我之前主要是開發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來進行緩衝就顯的很重要了。