Blog purpose for android basic example for android app developer. any query please my contact

Saturday 3 February 2024

Android kotlin flash screen example

 kotlin flash screen example


Create a new Android project:

Open Android Studio, go to File -> New -> New Project, and follow the wizard to create a new project.


Add an image for the splash screen:

Place an image file (e.g., splash_image.png) in the res/drawable folder.


Modify res/values/styles.xml:

Open the styles.xml file and add a new style for the splash screen:


1.resource.xml


<resources>


    <!-- Base application theme -->

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

        <!-- Customize your theme here. -->

        <item name="colorPrimary">@color/colorPrimary</item>

        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>

        <item name="colorAccent">@color/colorAccent</item>

    </style>


    <!-- Splash screen theme -->

    <style name="SplashTheme" parent="Theme.AppCompat.Light.NoActionBar">

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

    </style>


</resources>



2. AndroidManifest.xml:

Update the MainActivity theme to use the splash screen theme (SplashTheme). Set the MainActivity launch mode to singleTop to prevent the recreation of the activity when it's already at the top of the stack.


xml


<activity

    android:name=".MainActivity"

    android:label="@string/app_name"

    android:theme="@style/SplashTheme"

    android:launchMode="singleTop">

    <intent-filter>

        <action android:name="android.intent.action.MAIN" />


        <category android:name="android.intent.category.LAUNCHER" />

    </intent-filter>

</activity>


In the MainActivity class, add a Handler to delay the actual content display:


3. MainActivity.Kotlin:

import android.content.Intent

import android.os.Bundle

import android.os.Handler

import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)


        // Delay for 2 seconds and then start the actual activity

        Handler().postDelayed({

            startActivity(Intent(this, ActualActivity::class.java))

            finish()

        }, 2000)

    }

}

Replace ActualActivity::class.java with the actual activity you want to launch after the splash screen.


Create the ActualActivity:

Create another activity (e.g., ActualActivity.kt) that represents the main content of your app.


That's it! This example demonstrates a simple splash screen with a delay of 2 seconds before launching the actual activity. Customize it further based on your specific requirements.

No comments:

Post a Comment