import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.widget.Button
import android.widget.TextView
class MainScreen : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button = findViewById<Button>(R.id.goGreetingButton)
button.setOnClickListener {
val intent = Intent(this, GreetingScreen::class.java)
intent.putExtra("name", "Alice")
startActivity(intent)
}
}
}
class GreetingScreen : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_greeting)
val greetingText = findViewById<TextView>(R.id.greetingTextView)
val name = intent.getStringExtra("name") ?: "Guest"
greetingText.text = "Hello, $name!"
}
}We created two screens: MainScreen and GreetingScreen. In MainScreen, we set a click listener on the button. When clicked, it creates an Intent to start GreetingScreen and passes a string extra with key "name" and value "Alice".
In GreetingScreen, we retrieve the passed name from the intent extras. If no name is passed, we use "Guest" as default. Then we update the TextView to show a greeting message with the name.
This shows how to pass simple data between screens in Android using Intent extras.