0
0
Android-kotlinHow-ToBeginner ยท 3 min read

How to Navigate Between Activities in Android: Simple Guide

To navigate between activities in Android, use an Intent to specify the target activity and call startActivity(). This launches the new screen, allowing users to move from one activity to another.
๐Ÿ“

Syntax

Use an Intent to specify the current and target activities, then call startActivity() to navigate.

  • Intent(this, TargetActivity::class.java): Creates an intent from current to target activity.
  • startActivity(intent): Starts the target activity.
kotlin
val intent = Intent(this, TargetActivity::class.java)
startActivity(intent)
๐Ÿ’ป

Example

This example shows a button in MainActivity that navigates to SecondActivity when clicked.

kotlin
class MainActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val button = findViewById<Button>(R.id.buttonNavigate)
    button.setOnClickListener {
      val intent = Intent(this@MainActivity, SecondActivity::class.java)
      startActivity(intent)
    }
  }
}

class SecondActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_second)
  }
}
Output
When the button is tapped, the app opens SecondActivity screen.
โš ๏ธ

Common Pitfalls

Common mistakes include:

  • Not declaring the target activity in AndroidManifest.xml.
  • Using wrong context instead of this or ActivityName.this.
  • Forgetting to call startActivity() after creating the intent.
kotlin
/* Wrong: Missing startActivity call */
val intent = Intent(this, SecondActivity::class.java)
// startActivity(intent) is missing

/* Correct: */
val intent = Intent(this, SecondActivity::class.java)
startActivity(intent)
๐Ÿ“Š

Quick Reference

ActionCode Snippet
Create Intentval intent = Intent(this, TargetActivity::class.java)
Start ActivitystartActivity(intent)
Declare Activity in Manifest
โœ…

Key Takeaways

Use Intent and startActivity() to navigate between activities.
Always declare new activities in AndroidManifest.xml.
Use the correct context when creating the Intent.
Remember to call startActivity() after creating the Intent.
Test navigation to ensure the target activity opens correctly.