このページには広告が含まれる場合があります。
アプリを開いたときに、メイン画面が開くまでの間に表示されるこんな感じの画面(Splash ScreenとかLauncher Screenとか言います)を表示させて、見栄えをちょっとよくするための方法です。
もくじ
1.Sprash Screenに表示させるロゴ画像をdrawableフォルダに格納
これは、通常の画像を格納するやり方と同じですので割愛
2.Sprash Screen用のxmlファイルをdrawableフォルダに作成
こんな感じで(res => drawable => launcher_screen.xml)
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="https://schemas.android.com/apk/res/android"> <item android:drawable="@color/colorPrimaryDark" /> ← 背景色 <item> <bitmap android:gravity="center" ← 画面の真ん中に android:src="@drawable/meiso_logo" /> ← ロゴ画像を置く </item> </layer-list>
「layer-list」というのは、複数の画像を1つの画像にまとめてくれる属性らしいです。
3.Sprash Screen用のテーマをstyles.xmlに設定
この例では、「AppTheme.Launcher」という名前をつけました。
<style name="AppTheme.Launcher"> <item name="android:windowBackground">@drawable/launch_screen</item> </style>
4.アプリが開いた時に起動するActivityのstyleを3で設定したものにマニフェストファイルで設定
こんな感じで(17行目)
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="net.minpro.meiso"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme" android:name=".MyApplication"> <activity android:name=".view.MainActivity" android:label="@string/app_name" android:theme="@style/AppTheme.Launcher" ← コレ android:screenOrientation="portrait"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
5.アプリのメイン画面が開いたら、元のテーマに戻すための設定をソースコードで行う
この例の場合は、MainActivityで、superコールの前でsetThemeメソッドを入れます。
class MainActivity : AppCompatActivity(){ override fun onCreate(savedInstanceState: Bundle?) { setTheme(R.style.AppTheme) //superコールの前にスタイル設定(LauncherScreenを入れたので) super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) }
他にも色々やり方はあるようですが、一番簡単なのはこのやり方のようですね。
超簡単ですので、見栄えをちょっと良くするのに使えるのではないでしょうか。
(詳しい解説を下の動画でしていますので、よろしければご覧ください)