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

Android 啟動畫面實作:讓歡迎頁停留兩秒半再進主頁

編輯:關於 Android 開發

打開 App 先看到一張 logo 或歡迎頁,是老派卻仍然有效的做法。原理其實非常單純:開一個背景執行緒睡一會兒,醒來後跳轉到下一個 Activity,然後把自己關掉。

歡迎頁的 Activity

public class WelComeActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.welcome);
        Start();
    }

    public void Start() {
        new Thread() {
            public void run() {
                try {
                    Thread.sleep(2500);        // 停留 2.5 秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Intent intent = new Intent();
                intent.setClass(WelComeActivity.this, LoginActivity.class);
                startActivity(intent);
                finish();                      // 關掉自己,避免按返回鍵回到歡迎頁
            }
        }.start();
    }
}

歡迎頁的版面

最省事的做法是直接把背景設成一張圖,不需要任何子 View:

<?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"
    android:background="@drawable/logo">
</LinearLayout>

三個實務上值得補強的地方

第一,finish() 千萬別漏。少了它,使用者在登入頁按返回鍵會又回到歡迎頁,再等兩秒半,體驗很差。

第二,睡眠時間別寫死。比較好的做法是讓它等「真正該等的事」完成——例如初始化 SDK、拉取設定檔——用 CountDownLatch 或 Future 等待結果,事情做完立刻走,沒做完才顯示載入動畫。單純為了展示 logo 而硬睡兩秒,等於免費送使用者一段焦慮。

第三,別忘了螢幕方向與主題。若歡迎頁要在未載入任何版面之前就顯示,Android 12 以後有官方的 SplashScreen API(含 windowSplashScreenBackground 等屬性)可用,自訂 Activity 的舊做法在新版系統上會被系統啟動畫面覆蓋,值得改用官方機制以免畫面閃跳。

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