写启动界面Splash的正确姿势,解决启动白屏(转)

时间:2023-03-08 20:16:41

从我学习写第一个android项目以来,我都是这样写着启动界面:
  • 在里面做一些事,比如:第一次启动时拷贝数据。
  • 然后让启动界面一定待够一定时间,比如两秒三秒的。

就在前两天我打开app的时候,我感觉启动界面的时间太长了,而且为什么会先白屏一下然后进入启动界面。很多app都有启动界面,也有很多app没有启动界面,但是我发现这些没有启动界面的app,当我点击桌面那个icon的时候,也会先白屏一下,然后进入主页。

然后我决定做两件事:

  • 做完启动界面的事就进入首页,不故意睡了。
  • 消灭白屏(跟主题设置的关系也有可能是黑屏),在点击桌面app icon的瞬间开启启动界面,因为我点了美团,发现它是秒开的。。

如何消灭白屏

  1. 删除启动界面的xml布局,删除setContentView。
  2. 在res/drawable里写一个这种玩意:
    <?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android"><item><bitmapandroid:id="@+id/bitmap_splash"android:src="@mipmap/splash_bg"></bitmap></item><itemandroid:top="@dimen/splash_logo_marginTop"><bitmapandroid:gravity="top"android:src="@mipmap/splash_logo"></bitmap></item><itemandroid:bottom="80dp"><bitmapandroid:gravity="bottom"android:src="@mipmap/splash_word"></bitmap></item></layer-list>

    item有drawable属性,但是不能接收mipmap参数,所以我又包了bitmap。

  3. 在style里配置主题,我这里AppBaseTheme的parent是Theme.AppCompat.Light.NoActionBar,然后还有其他的一些配置。
    <style name="Splash" parent="AppBaseTheme">
    <item name="android:windowBackground">@drawable/splash</item>
    </style>
  4. 在manifest中splash的activity标签中配置主题:
    ...
    android:theme="@style/Splash"...
  5. 启动一下看看效果吧。

网上搜启动消除白屏的方法,有设置启动界面主题的背景为透明的,splash的xml布局还和以前一样,这样确实不白屏了,但是点击桌面上的icon开始会等一会splash才会出现,体验也不好。

参考

splash-screens-the-right-way