info@androidpaper.co.in

How to switch between different Activities in Android using Kotlin

To switch between different activities in Android using Kotlin, you can follow these steps:

Step 1: Create a new activity
First, create a new activity that you want to switch to. In Android Studio, right-click on the package where you want to create the new activity, and select "New" -> "Activity" -> "Empty Activity". Give the activity a name and click "Finish".

Step 2: Define a button in the layout XML
In the layout XML file of your current activity, add a button or any other view that you want to trigger the activity switch. For example:

<Button
    android:id="@+id/switchButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Switch Activity"
    />

Step 3: Set a click listener for the button
In your current activity's Kotlin file, find the button by its ID and set a click listener to handle the click event.

val switchButton = findViewById<Button>(R.id.switchButton)
switchButton.setOnClickListener {
    // Switch to the new activity
    val intent = Intent(this, SecondActivity::class.java)
    startActivity(intent)
}

Replace SecondActivity with the name of the activity you created in Step 1.
Step 4: Pass data between activities (optional)
If you want to pass data from the current activity to the new activity, you can add extra information to the intent before starting the new activity.

intent.putExtra("key", value)

Replace "key" with a unique identifier for the data and "value" with the actual value you want to pass.
Step 5: Retrieve data in the new activity (optional)
In the new activity, you can retrieve the data passed from the previous activity using the intent's extras.

val receivedValue = intent.getStringExtra("key")

Replace "key" with the same identifier you used in Step 4.
That's it! You have now implemented switching between activities in Android using Kotlin. Repeat these steps for any additional activities you want to switch to in your app.