본문 바로가기
Andorid Kotlin

액티비티간 데이터 주고 받기

by SimonLee 2024. 10. 2.

MainActivity

메인 액티비티 에서 인텐트를 생성하고 인텐트에 putExtra 함수를 통해서 서브 액티비티로 전송한다.

startAcitivity(intent)를 실행하면 전달만 하고

startActivity(intent, num)을 실행하면 리턴을 받는다.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(binding.root)

    with (binding) {
        button.setOnClickListener { view->
            var intent = Intent(this@MainActivity, SubActivity::class.java)
            intent.putExtra("from1", "hello bundle")
            intent.putExtra("from2", 2021)
            // startActivity(intent) 액티비티 전달 한다.
            startActivityForResult(intent, 99)
        }
    }
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    if (resultCode == Activity.RESULT_OK) {
        when (requestCode) {
            99 -> {
                data?.getStringExtra("returnValue")
                    ?. let { message ->
                        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
                    }
            }
        }
    }
}

main Activity XML

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/to1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="메인 액티비티"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="160dp"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="160dp"
        android:text="서브 액티비티 실행"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/to1" />
</androidx.constraintlayout.widget.ConstraintLayout>

 

 

SubActivity

Main Acitivity에서 전달 받은 변수를 intent.getXXExtra 함수를 통하여 전달 받는다.

Main Activity로 리턴할때는

intent를 생성하고 intent에 put 함수를 통하여 작성하고 setResult를 호출한다.

class SubActivity : AppCompatActivity() {
    val binding by lazy { ActivitySubBinding.inflate(layoutInflater)}
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        with (binding) {
            to1.text = intent.getStringExtra("from1")
            to2.text = intent.getIntExtra("from2", 0).toString()

            btnClose.setOnClickListener {
                val returnIntent = Intent()
                val message = editMessage.text.toString()
                returnIntent.putExtra("returnValue", message)
                setResult(Activity.RESULT_OK, returnIntent)
                finish()
            }
        }
    }
}

 

sub Activity XML

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="107dp"
        android:layout_marginTop="284dp"
        android:layout_marginEnd="108dp"
        android:text="서브 액티비티"
        android:textSize="34sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/to2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:layout_marginEnd="108dp"
        android:text="to22"
        android:textSize="24sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <TextView
        android:id="@+id/to1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:text="to1"
        android:textSize="24sp"
        app:layout_constraintTop_toBottomOf="@+id/textView2"
        tools:layout_editor_absoluteX="107dp" />

    <EditText
        android:id="@+id/editMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="93dp"
        android:layout_marginEnd="108dp"
        android:ems="10"
        android:hint="전달할 메시지를 입력하세요"
        android:inputType="text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        tools:layout_editor_absoluteY="413dp" />

    <Button
        android:id="@+id/btnClose"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="142dp"
        android:layout_marginTop="15dp"
        android:layout_marginEnd="178dp"
        android:text="액티비티 닫기"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editMessage" />
</androidx.constraintlayout.widget.ConstraintLayout>