you will not use a layout file. Instead, specify your splash screen’s background as the activity’s theme background. To do this, first create an XML drawable in res/drawable.
Note: all code below is available GitHub Link
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@color/gray"/>
<item>
<bitmap
android:gravity="center"
android:src="@mipmap/ic_launcher"/>
</item>
</layer-list>
Here, I’ve set up a background color and an image.
Next, you will set this as your splash activity’s background in the theme. Navigate to your styles.xml file and add a new theme for your splash activity:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>
<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
<item name="android:windowBackground">@drawable/background_splash</item>
</style>
</resources>
In your new SplashTheme, set the window background attribute to your XML drawable. Configure this as your splash activity’s theme in your AndroidManifest.xml:
<activity
android:name=".SplashActivity"
android:theme="@style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Finally, your SplashActivity class should just forward you along to your main activity:
public class SplashActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
Notice that you don’t even set up a view for this SplashActivity. The view comes from the theme. When you set up the UI for your splash activity in the theme, it is available immediately.
If you did have a layout file for your splash activity, that layout file would be visible to the user only after your app has been fully initialized, which is too late. You want the splash to be displayed only in that small amount of time before the app is initialized.