LoginSignup
23
28

More than 3 years have passed since last update.

Android &Kotlin:アプリを開いた時にロゴが一瞬出てくるやつ(スプラッシュ画面)を実装する

Posted at

記事の内容

Androidアプリのスプラッシュ画面をKotlinで実装していきます。
そもそもスプラッシュ画面って何?という方もいらっしゃると思いますが、スプラッシュ画面とは例えばあなたのスマホでツイッターのアプリをタップすると、タイムラインが表示されるまでの間ツイッターのロゴがしばらく表示されたりしませんか?あんな感じでアプリが起動するまでの時間をいい感じにごまかす画面がスプラッシュ画面と言われています。

実装手順

・activity_splash.xmlの構成
・SplashActivity.kt実装
・SplashActivityをManifestに追加

activity_splash.xmlの構成

activity_splash.xmlでは、スプラッシュ画面として表示したい画像やロゴを指定します。

まず、表示したい画像をres -> drawableに名前をつけて保存してください。
私はsplash_imageという名前で保存しました。

保存した画像を画面いっぱいに表示します。
コードは以下の通りです。

activity_splash.xml
<?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を実装していきます。
コードは以下の通りです。

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に以下を追加

AndroidManifest.xml
<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>

以上でなんとかなるはずです。

23
28
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
28