안드로이드(Kotlin)/기초/
Activity 전환 Intent (2) 결과값 받기
2020. 4. 30.
파일 구조
Main 컴포넌트 트리
texxtView -> id: message
button -> id: moveButton
Sub 컴포넌트 트리
textView -> id: extra
button -> id: okButton
Main 코드
package com.example.myexam1
import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
moveButton.setOnClickListener{
val intent = Intent(applicationContext,SubActivity::class.java)
intent.putExtra("MESSAGE","Main에서 왔습니다")
startActivityForResult(intent,1004)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode == 1004 && resultCode == Activity.RESULT_OK){
message.text = data?.getStringExtra("MESSAGE")
}
}
}
Sub 코드
package com.example.myexam1
import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_sub.*
class SubActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sub)
val intent = intent
extra.text = intent.getStringExtra("MESSAGE")
okButton.setOnClickListener{
val intent = Intent()
intent.putExtra("MESSAGE","돌아왔습니다")
setResult(Activity.RESULT_OK,intent)
finish()
}
}
}