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
thisorActivityName.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
| Action | Code Snippet |
|---|---|
| Create Intent | val intent = Intent(this, TargetActivity::class.java) |
| Start Activity | startActivity(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.