package com.example.activityresults
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private lateinit var nameTextView: TextView
private lateinit var enterNameButton: Button
private lateinit var getNameLauncher: ActivityResultLauncher<Intent>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
nameTextView = findViewById(R.id.nameTextView)
enterNameButton = findViewById(R.id.enterNameButton)
getNameLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val name = result.data?.getStringExtra("name") ?: ""
nameTextView.text = "Name: $name"
}
}
enterNameButton.setOnClickListener {
val intent = Intent(this, EnterNameActivity::class.java)
getNameLauncher.launch(intent)
}
}
}
// Second activity to enter name
import android.app.Activity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
class EnterNameActivity : AppCompatActivity() {
private lateinit var nameEditText: EditText
private lateinit var saveButton: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_enter_name)
nameEditText = findViewById(R.id.nameEditText)
saveButton = findViewById(R.id.saveButton)
saveButton.setOnClickListener {
val name = nameEditText.text.toString()
val resultIntent = intent
resultIntent.putExtra("name", name)
setResult(Activity.RESULT_OK, resultIntent)
finish()
}
}
}We use registerForActivityResult with StartActivityForResult to launch the second screen and get the result back.
When the user taps the 'Enter Name' button, we start EnterNameActivity.
In EnterNameActivity, the user types a name and taps Save. We put the name into the result intent and finish the activity.
Back in MainActivity, the launcher callback receives the result and updates the TextView to show the entered name.