经过一段时间的调研,我找到了许多Android中的splash (launch) screen实现方法,但是开发者通常是使用一个延时执行的Runnable来解决问题。这种方式我认为并不友好,不应该让用户为了等待而等待,让App不加载任何东西而仅仅延时执行任务。这里将展示一种很棒的解决方式,这种方式代码改动很小:
直接看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,每天推送移动开发前沿技术文章: