SubActivity 실행 및 데이터 넘기기
MainActivity.kt
class MainActivity : AppCompatActivity() {
private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
val intent = Intent(this, SubActivity::class.java)
intent.putExtra("data1", "First Data")
intent.putExtra("data2", 2022)
binding.goToSubBtn.setOnClickListener { startActivity(intent) }
}
}
SubActivity.kt
class SubActivity : AppCompatActivity() {
private val binding by lazy { ActivitySubBinding.inflate(layoutInflater) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.Data1.text = intent.getStringExtra("data1")
binding.Data2.text = "${intent.getIntExtra("data2", 0)}"
}
}
MainAcitivity에서 값 돌려받기
SubActivity.kt
class SubActivity : AppCompatActivity() {
private val binding by lazy { ActivitySubBinding.inflate(layoutInflater) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.Data1.text = intent.getStringExtra("data1")
binding.Data2.text = "${intent.getIntExtra("data2", 0)}"
binding.exitBtn.setOnClickListener {
val returnIntent = Intent()
returnIntent.putExtra("returnValue", binding.returnMessage.text.toString())
setResult(RESULT_OK, returnIntent)
finish()
}
}
}
MainActivity.kt
class MainActivity : AppCompatActivity() {
private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
val activityResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == RESULT_OK) {
val message = it.data?.getStringExtra("returnValue")
binding.textView2.text = message
}
}
val intent = Intent(this, SubActivity::class.java)
intent.putExtra("data1", "First Data")
intent.putExtra("data2", 2022)
binding.goToSubBtn.setOnClickListener { activityResult.launch(intent) }
}
}
build.gradle (Module: Activity.app)
dependencies {
def dependency_version = "1.3.1"
implementation "androidx.activity:activity-ktx:$dependency_version"
implementation "androidx.fragment:fragment-ktx:$dependency_version"
...
}