Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 啟動閃屏(Splash Screen)實作教學

編輯:關於 Android 程式設計

閃屏,也就是 SplashScreen,中文常稱作啟動畫面。App 打開時先顯示一張圖或一段動畫,停留數秒後自動跳進主畫面,是絕大多數應用都會用到的手法。

為什麼用 Handler 就足夠

Android 實作閃屏其實非常單純,只要借助 Handler 的 postDelayed() 即可。這個方法接收兩個參數:第一個是要延後執行的 Runnable,裡面寫著延遲結束後想做的事;第二個是延遲的毫秒數。把「跳轉到主畫面並關掉自己」放進 Runnable,時間設為 3000,就得到一個停留三秒的啟動畫面。

Java 程式碼

package com.mstar;

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

public class ActSplashScreen extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shan);

        // 閃屏核心:延遲 3 秒後導向主畫面
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(ActSplashScreen.this, DialogTest.class);
                startActivity(intent);
                // 關閉啟動畫面,避免使用者按返回鍵又回到閃屏
                ActSplashScreen.this.finish();
            }
        }, 3000);
    }
}

版面配置

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="閃一下" />
</LinearLayout>

實務上的補充

記得一定要呼叫 finish(),否則使用者在主畫面按返回鍵時會被送回閃屏,體驗很差。另外,若閃屏期間需要載入網路資料,建議改用非同步任務並在資料回來後再跳轉,而不是死等固定秒數,這樣可以避免「畫面閃過了、資料還沒好」的尷尬情況。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved