アプリ起動時にスプラッシュ画面を表示させる方法

アプリケーション起動処理中に表示する画像をスプラッシュスクリーン(Splash screen)といいます。
このスプラッシュ画面の実装方法ですが、iPhoneアプリと違いAndroidアプリでは標準でスプラッシュ画面を表示させるものはないので、単純に起動時に画面を表示させる動作を実装します。

まずはスプラッシュ画面のレイアウトのXML(splash.xml)を作成します。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<ImageView 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:scaleType="centerInside"
    android:src="@drawable/splash"
    />
</LinearLayout>

ここでres/drawable/splash.pngの画像を全画面で表示させるように指定しています。

スプラッシュ画面用のアクティビティクラス(SplashActivity.java)を作成します。

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Window;

public class SplashActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// タイトルを非表示にします。
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		// splash.xmlをViewに指定します。
		setContentView(R.layout.splash);
		Handler hdl = new Handler();
		// 500ms遅延させてsplashHandlerを実行します。
		hdl.postDelayed(new splashHandler(), 500);
	}
	class splashHandler implements Runnable {
		public void run() {
			// スプラッシュ完了後に実行するActivityを指定します。
			Intent intent = new Intent(getApplication(), MainActivity.class);
			startActivity(intent);
			// SplashActivityを終了させます。
			SplashActivity.this.finish();
		}
	}
}

AndroidManifest.xmlを変更して、起動時にSplashActivityが実行されるように変更します。

[参考記事] 最初に呼び出されるJavaファイル(Activity)を指定する方法

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.ghana"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SplashActivity"
                  android:label="@string/app_name" android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity"></activity>

    </application>
</manifest>

これでアプリ起動時に、スプラッシュ画面が表示されます。

関連記事

スポンサーリンク

SDカードの空き容量を調べる方法

ホームページ製作・web系アプリ系の製作案件募集中です。

上に戻る