如何建立登入過程的畫面(SplashScreen)

如何建立登入過程的畫面(SplashScreen)

情境

其實會需要啟動畫面
有一種說法是早期PC時代
由於記憶體很少
要載入到作業系統
需要一段時間
久而久之, 啟動畫面變成一種習慣

不過現在看起來, 其實啟動畫面還是有它的好處
例如在啟動畫面可以展示公司/產品的LOGO
打個廣告, 順便把一些使用者常用的資料
在開啟程式之前就先抓好或啟動起來
這樣一來使用者一旦進入程式
就可以很迅速地將程式開啟

如果想要在一開始的畫面
就先跳出公司或產品的 logo 或者顯示進度條
該怎麼做呢?

程式碼說明

首先建立你要放的Logo畫面

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="example.givemepass.splashscreendemo.SplashActivity">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:contentDescription="@string/app_name"
        android:src="@drawable/butterfly" />
</RelativeLayout>

其實就是一張圖, 也有app是做成動畫, 做法相同。

然後建立一個新的Activity, 讓它進來這個畫面的時候停止三秒, 因為這個只是demo用, 這邊就可以做你希望載入app的時候, 需要預先載入的資料。
SplashActivity

public class SplashActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                startActivity(new Intent().setClass(SplashActivity.this, MainActivity.class));
            }
        }, 3000);
    }
}

MainActivity

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

並且設定成Launcher

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity android:name=".SplashActivity" >
        <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>

這樣就簡單完成一個模擬秀logo的demo了。



程式碼