1. Create a New Project
- Open Android Studio → New Project → Empty Activity.
- Let’s say it creates MainActivity by default.
2. Add Another Activity
- Right-click on
javafolder → New → Activity → Empty Activity. - Name it
SecondActivity. - Android will create:
SecondActivity.kt(Kotlin file)activity_second.xml(layout file)
3. Register the New Activity in AndroidManifest.xml
This step is usually done automatically, but confirm it’s there:
<activity android:name=".SecondActivity" />
4. Design Layouts
Main Screen (with a Button)
📌 activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="20dp">
<Button
android:id="@+id/buttonSwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to Second Activity"/>
</LinearLayout>
Second Screen
📌 activity_second.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<TextView
android:id="@+id/textViewMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to Second Activity!"
android:textSize="20sp"/>
</LinearLayout>
5. Add Switching Logic
MainActivity (Start SecondActivity)
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button = findViewById<Button>(R.id.buttonSwitch)
button.setOnClickListener {
// Create an intent to move to SecondActivity
val intent = Intent(this, SecondActivity::class.java)
startActivity(intent) // Switch activity
}
}
}
SecondActivity (Optional Back Button)
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
// By default, Android adds a Back button in the top bar.
// Or user can press phone's back button to return.
}
}
6. Running the App
- When you click “Go to Second Activity”, it will switch screens.
- Pressing the back button returns to MainActivity.
🔑 Extra Tips
- To finish current activity when switching:
startActivity(intent) finish() // closes MainActivity so user can’t go back - To pass data along with switching:
intent.putExtra("KEY", "Hello Second Activity") - To receive data back from another activity → use
startActivityForResult()(orActivityResultLauncherin modern apps).
