Android App 中正確地使用 Splash Screen(譯)

wutongke發表於2017-03-13

經過一段時間的調研,我找到了許多Android中的splash (launch) screen實現方法,但是開發者通常是使用一個延時執行的Runnable來解決問題。這種方式我認為並不友好,不應該讓使用者為了等待而等待,讓App不載入任何東西而僅僅延時執行任務。這裡將展示一種很棒的解決方式,這種方式程式碼改動很小:

Android App 中正確地使用 Splash Screen(譯)

直接看code

首先我們設計一個splash screen layout,我這裡把App的logo放置在中間,使用App的主色值作為背景,創造了一個drawable:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:opacity="opaque">
    <item android:drawable="@color/colorPrimary"/>
    <item>
        <bitmap
            android:gravity="center"
            android:src="@drawable/icon"/>
    </item>
</layer-list>複製程式碼

然後我們定義一個theme,使用以上的drawable作為theme屬性windowBackground的值:

<resources>
  <style name="SplashTheme" parent="AppTheme">
    <item name="android:windowBackground">@drawable/splash</item>
  </style>
</resources>複製程式碼

之後,我們把以上theme作為MainActivity的theme:

<activity android:name=".activities.MainActivity"
  android:theme="@style/SplashTheme">
  <intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
  </intent-filter>
</activity>複製程式碼

最後,我們在MainActivity的onCreate方法中使用真實的theme:

public class MainActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // Make sure this is before calling super.onCreate
    setTheme(R.style.AppTheme);
    super.onCreate(savedInstanceState);
  }
}複製程式碼

總結

使用以上的方式,splash screen將在App初始化過程中展示,而且不用為splash建立額外的activity。Splash screen的展示時間與activity的建立時間相關。

另外:祝自己生日快樂。

閱讀原文:android.jlelse.eu/launch-scre…

歡迎關注公眾號wutongke,每天推送移動開發前沿技術文章:

Android App 中正確地使用 Splash Screen(譯)
wutongke

相關文章