[해결방법]
1. 변수를 하나 생성하고 registerForActivityResult(ActivityResultContracts.StartActivityForResult( )){ }를 대입
2. 중괄호 안에 기존의 onActivityResult( )에서 수행했던 코드를 넣음
val getAction = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
val message = it.data?.getStringExtra("returnValue")
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}
3. startActivityForReslut(intent) 대신에 1번에서 생성한 변수.launch(intent)로 교체
binding.btnStart.setOnClickListener {
getAction.launch(intent)
}
[The old way]
class MainActivity : AppCompatActivity() {
val binding by lazy {ActivityMainBinding.inflate(layoutInflater)}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// deprecated
if(resultCode == RESULT_OK){
when(requestCode){
99 -> {
val message = data?.getStringExtra("returnValue")
Toast.makeText(this,message,Toast.LENGTH_LONG).show()
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
val intent = Intent(this, SubActivity::class.java)
intent.putExtra("from1","Hello Bundle")
intent.putExtra("from2", 2021)
binding.btnStart.setOnClickListener {
startActivityForResult(intent, 99)
// deprecated
}
}
}
[The new way - kotlin]
class MainActivity : AppCompatActivity() {
val binding by lazy {ActivityMainBinding.inflate(layoutInflater)} /* override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { //super.onActivityResult(requestCode, resultCode, data) // deprecated if(resultCode == RESULT_OK){ when(requestCode){ 99 -> { val message = data?.getStringExtra("returnValue") Toast.makeText(this,message,Toast.LENGTH_LONG).show() } } } }*/
val getAction = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
val message = it.data?.getStringExtra("returnValue")
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
val intent = Intent(this, SubActivity::class.java)
intent.putExtra("from1","Hello Bundle")
intent.putExtra("from2", 2021)
binding.btnStart.setOnClickListener { /* startActivityForResult(intent, 99) // deprecated*/
getAction.launch(intent)
}
}
}
한글로는 아래에 설명이 잘 되어 있는듯
https://modelmaker.tistory.com/18
'Coding > Android' 카테고리의 다른 글
[Android Studio] Constraint Widget : xml file 디자인모드 속성 창에서 레이아웃의 길이를 빠르게 변경하기 (0) | 2021.05.30 |
---|---|
Namespace is not Bound in Android Studio (0) | 2021.01.27 |
댓글