在启动时摆脱白屏

时间:2017-10-07 12:42:29

标签: android xml android-drawable splash-screen

当我的Android应用程序启动时,我一直在网上寻找避免白屏的正确方法 - 用闪屏替换它。 我找到了使用

等样式的解决方案
<style name="AppTheme.SplashTheme">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowActionBar">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowIsTranslucent">true</item>
</style>

但在我的情况下,这只会延迟视图外观,因为应用程序不起作用(视图在几秒后膨胀)。我不想要一些持续了几秒钟的视图我已经决定,我只是想在我的应用程序需要加载时将空白屏幕替换为自定义。 获得所需行为的唯一方法是将drawable作为背景放置在SplashscreenActivity的样式中。

<item name="android:windowBackground">@drawable/background_splash</item>

现在,我不希望将图像作为背景放置 - 因为屏幕的分辨率不同 - 而是设置xml布局。 这可能吗?在不延迟视图外观的情况下摆脱空白屏幕的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

你应该按照以下方式进行

  • res/drawable文件夹中创建一个包含以下内容的xml文件。这将作为你的启动画面。我们将其命名为splash.xml

    <?xml version="1.0" encoding="utf-8"?>
    
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
       <item android:drawable="@color/colorPrimary" />
       <item>
            <bitmap android:src="@drawable/splash_logo"
        android:gravity="center" />
      </item>
    </layer-list>
    
  • 然后,您需要为启动视图指定不带标题栏的style/theme,因此请在style文件的style.xml下方添加{。}}。

    <style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
        <item name="android:windowBackground">@drawable/splash</item>
    </style>
    
  • AndroidManifest.xml更改theme launcher activity以使用SplashTheme

        <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/SplashTheme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
    
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    
  • 最后在launcher activity(在我的示例MainActivity中)将主题更改回默认应用主题,通常名为AppTheme

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.AppTheme)
        super.onCreate(savedInstanceState);    
        ...
    }
    

就是这样!现在运行您的应用程序,看到没有白屏了。

参考:我使用this postthis one来提供上述代码示例。