0
0
Android Kotlinmobile~5 mins

Intent for activity navigation in Android Kotlin

Choose your learning style9 modes available
Introduction

We use intents to move from one screen to another in an app. It helps users go to different parts of the app easily.

When you want to open a new screen after a button click.
To move from a login screen to the home screen after successful login.
When you want to show details of an item selected from a list.
To switch between different features of the app.
Syntax
Android Kotlin
val intent = Intent(this, TargetActivity::class.java)
startActivity(intent)

Intent is a message to start another screen.

this refers to the current screen, and TargetActivity::class.java is the screen to open.

Examples
Basic example to open SecondActivity from current activity.
Android Kotlin
val intent = Intent(this, SecondActivity::class.java)
startActivity(intent)
Send extra data (itemId) to the new screen.
Android Kotlin
val intent = Intent(this, DetailActivity::class.java)
intent.putExtra("itemId", 123)
startActivity(intent)
Open a web page using an intent.
Android Kotlin
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse("https://www.example.com")
startActivity(intent)
Sample App

This app has two screens. When you tap the button on the first screen, it opens the second screen.

Android Kotlin
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.widget.Button

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, SecondActivity::class.java)
            startActivity(intent)
        }
    }
}

class SecondActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)
    }
}
OutputSuccess
Important Notes

Always declare your activities in the AndroidManifest.xml file.

You can pass data between activities using putExtra and retrieve it with getIntent().getExtras().

Intents can also be used to start system actions like opening a web page or calling a phone number.

Summary

Intent helps move between screens in an app.

Use Intent(this, TargetActivity::class.java) to create an intent.

Call startActivity(intent) to open the new screen.