Simple Splash Screen in Android
In this blog, We are going to implement Simple Splash Screen in Android using styles.
There are two commonly used methods to implement the splash screen in android.
1st Method (Bad Way): We can add splash by using timmer. In this approach, We create a new thread for the delay for a specific time like 2/3 sec. Once the delay is completed then it opens the main activity and finishes itself by calling finish().
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class SplashActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash_screen) Handler().postDelayed(Runnable { //This method will execute when the timer is over // Start MainActivity val i = Intent(this@SplashScreenActivity, MainActivity::class.java) startActivity(i) // close this activity finish() }, 3000) } } |
The above-mentioned approach is not correct.
2nd Method (Right way): Using a Launcher Theme. Application theme
is instantiated before the layout is created. So, we will just set a custom theme in Manifest for our splash activity.
Step 1:
First of all, We have to create a drawable resource file that must be layer-list type. In that, we will use a bitmap tag to show the image.
drawable/splash_background.xml
1 2 3 4 5 6 7 8 9 10 |
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@android:color/white"></item> <item> <bitmap android:gravity="center" android:src="@drawable/splash_screen" /> </item> </layer-list> |
Step 2:
Create a new Style for SplashActivity in res/values/themes.xml
1 2 3 4 5 6 |
<?xml version="1.0" encoding="utf-8"?> <resources> <style name="mySplashStyle" parent="Theme.MaterialComponents.Light.NoActionBar"> <item name="android:windowBackground">@drawable/splash_background</item> </style> </resources> |
Step 3:
Set “mySplashStyle” the theme for SplashActivity in AndroidManifest.xml
1 2 3 4 5 6 7 8 |
<activity android:name=".SplashActivity" android:theme="@style/mySplashStyle"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> |
Step 4:
Launch the MainActivity by using Intent in onCreate() and finish the SplashActivity.
1 2 3 4 5 6 7 8 9 |
class SplashActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash_screen) val i = Intent(this@SplashActivity, MainActivity::class.java) startActivity(i) finish() } } |
Here we have done. I hope, this blog will be helpful to you.
My Other Blogs: https://mobikul.com/author/anandkashyap/