記事の内容
Androidアプリのスプラッシュ画面をKotlinで実装していきます。
そもそもスプラッシュ画面って何?という方もいらっしゃると思いますが、スプラッシュ画面とは例えばあなたのスマホでツイッターのアプリをタップすると、タイムラインが表示されるまでの間ツイッターのロゴがしばらく表示されたりしませんか?あんな感じでアプリが起動するまでの時間をいい感じにごまかす画面がスプラッシュ画面と言われています。
実装手順
・activity_splash.xmlの構成
・SplashActivity.kt実装
・SplashActivityをManifestに追加
activity_splash.xmlの構成
activity_splash.xml
では、スプラッシュ画面として表示したい画像やロゴを指定します。
まず、表示したい画像をres -> drawable
に名前をつけて保存してください。
私はsplash_image
という名前で保存しました。
保存した画像を画面いっぱいに表示します。
コードは以下の通りです。
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/splash_image"
tools:context=".SplashActivity">
</androidx.constraintlayout.widget.ConstraintLayout>
SplashActivity.ktの実装
次に、SplashActivity.kt
を実装していきます。
コードは以下の通りです。
package com.iroha168.gamancounter
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
class SplashActivity : AppCompatActivity() {
private val handler = Handler()
private val runnable = Runnable {
// ログイン済か未ログインかを判定
val user = Firebase.auth.currentUser
if (user != null) {
val intent = Intent(this, CountPageActivity::class.java)
startActivity(intent)
finish()
} else {
val intent = Intent(this, AuthenticationActivity::class.java)
startActivity(intent)
finish()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setTheme(R.style.SplashTheme)
handler.postDelayed(runnable, 1000)
}
override fun onStop() {
super.onStop()
handler.removeCallbacks(runnable)
}
}
上記のコードは、スプラッシュ画面を表示した後に、ユーザーがログイン状態であればホーム画面的なところに画面遷移し、ログイン状態でなければGoogle認証画面(ログイン画面)に画面遷移するというロジックです。
SplashActivityをManifestに追加
Manifestに以下を追加
<activity
android:name=".SplashActivity"
android:theme="@style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
以上でなんとかなるはずです。