根据Google 的建议 Here,您不应阻止此白屏启动。您可以使用此主题属性来关闭系统进程在启动应用程序时绘制的初始空白屏幕。
<item name="android:windowDisablePreview">true</item>
但是,不建议使用此方法,因为它可能会导致比不抑制预览窗口的应用程序更长的启动时间。此外,它会迫使用户在活动启动时等待没有反馈,让他们怀疑应用程序是否正常运行。
他们建议使用活动的 windowBackground 主题属性为启动活动提供简单的自定义可绘制对象,而不是禁用预览窗口。
因此,这里是推荐的解决方案:
首先,创建一个新的可绘制文件,例如 startup_screen.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" android:opacity="opaque">
<!-- The background color, preferably the same as normal theme -->
<item android:drawable="@android:color/white"/>
<!-- Product logo - 144dp color version of App icon -->
<item>
<bitmap
android:src="@drawable/logo"
android:gravity="center"/>
</item>
</layer-list>
其次,从您的样式文件中引用它。如果您使用夜间模式。在两个themes.xml 文件中添加它。
<!-- Start Up Screen -->
<style name="AppThemeLauncher" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<item name="android:statusBarColor" tools:targetApi="l">@color/lightGray</item>
<item name="android:windowBackground">@drawable/startup_screen</item>
</style>
如果您注意到,我添加了 statusBarColor 属性来根据我的自定义设计更改状态栏的颜色。
然后,在您当前的活动中添加AppThemeLauncher主题。
<activity
android:name=".MainActivity"
android:theme="@style/AppThemeLauncher"/>
如果您想转换回您的正常主题,请在调用 super.onCreate() 和 setContentView() 之前调用 setTheme(R.style.AppTheme):
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
// Make sure this is before calling super.onCreate
setTheme(R.style.AppTheme)
super.onCreate(savedInstanceState)
// ...
}
}