MvvmCross (現在 v4.14)をセットアップした Xamarin.Android プロジェクトは、はじめからスプラッシュスクリーンが実装されています。
ただ、セットアップ時に配置されている splash.png を差し替えただけでは、Android 画面比率に合わせて画像がゆがんで表示されてしまうため、正しく表示できるよう修正します。
初期状態
はじめに、スプラッシュスクリーンに関するファイルは次の通り。
- SplashScreen.cs
- Resources/drawable/splash.png
- Resources/layout/SplashScreen.axml
- Resources/values/SplashStyle.xml
MvxSplashScreenActivity を継承した SplashScreen クラスが最初に呼び出されます。ここで SplashScreen.axml にある Theme.Splash スタイルと、SplashStyle.xml 画面を指定しています。
namespace MapApp.Droid
{
[Activity(
Label = "Sample"
, MainLauncher = true
, Icon = "@mipmap/icon"
, Theme = "@style/Theme.Splash"
, NoHistory = true
, ScreenOrientation = ScreenOrientation.Portrait)]
public class SplashScreen : MvxSplashScreenActivity
{
public SplashScreen()
: base(Resource.Layout.SplashScreen)
{
}
}
}
SplashStyle.xml で、splash.png を背景として指定しています。
<resources>
<style name="Theme.Splash" parent="android:Theme">
<item name="android:windowBackground">@drawable/splash</item>
<item name="android:windowNoTitle">true</item>
</style>
</resources>
SplashScreen.axml では、Loading... のテキストを表示するよう記述しています。
<LinearLayout xmlnsandroid="http://schemas.android.com/apk/res/android"
androidorientation="vertical"
androidlayout_width="fill_parent"
androidlayout_height="fill_parent">
<TextView
androidlayout_width="fill_parent"
androidlayout_height="wrap_content"
androidtext="Loading...." />
</LinearLayout>
アプリを起動すると、splash.png が表示され、続いて SplashScreen.axml のテキストが表示されます。
問題点
splash.png が、画面比率に合わせてゆがんで表示されます。
9-patch 画像に置き換えても、SplashScreen.axml のテキストが表示されるときに背景画像がゆがみます。
解決策
SplashStyle.xml で指定する背景を、画像ファイルではなく、次のような xml ファイルに変えます。
SplashLayer.xml という名前で drawable フォルダーに保存します。
xml version="1.0" encoding="utf-8"
<layer-list xmlnsandroid="http://schemas.android.com/apk/res/android">
<item>
<shape
androidshape="rectangle">
<solid
androidcolor="@color/primary" />
</shape>
</item>
<item>
<bitmap
androidgravity="center"
androidsrc="@drawable/splash" />
</item>
</layer-list>
SplashStyle.xml を編集し、@drawable/splashlayer を指定します。
<resources>
<style name="Theme.Splash" parent="android:Theme">
<item name="android:windowBackground">@drawable/splashlayer</item>
<item name="android:windowNoTitle">true</item>
</style>
</resources>
以上です。