Learn to Live and Live to Learn

IT(たまにビジネス)に関する記事を読んで、考えて、使ってみたことをまとめる場。

スプラッシュ画像の表示方法

アプリを立ち上げたときに出てくるスプラッシュ画像。
設定してみました。

① 最初に表示したい面を用意します。
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"
    android:gravity="center"
    >
<ImageView 
    android:layout_width="90dp" 
    android:layout_height="90dp" 
    android:scaleType="fitCenter"
    android:src="@drawable/splash"
    />
</LinearLayout>

② スプラッシュ画像=splash.xmlを出すアクティビティを記述。
SplashActivity.java

package パッケージ名;

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 handler = new Handler();
		// 500ms遅延させてsplashHandlerを実行。
		handler.postDelayed(new splashHandler(), 500);

	}

	class splashHandler implements Runnable {
		public void run() {
         // MainActivityはいつも一番はじめに呼ばれるやつです。
			Intent intent = new Intent( getApplication(), MainActivity.class);
			startActivity(intent);
			SplashActivity.this.finish();
		}
	}
}

③ はじめにSplashActivity.javaを呼ぶようマニフェストファイルを書き換える。
Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="パッケージ名"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="17" />
    
    <application
        android:allowBackup="true"
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="SplashActivity"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.DeviceDefault.Light" >
            <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>

カッコよく出ました!


参考
アプリ起動時にスプラッシュ画面を表示させる方法 - [サンプルコード/Androidアプリ] ぺんたん info