상세 컨텐츠

본문 제목

[Kotlin] 액티비티(Activity) 사이에 값 주고 받기

IT/기초

by SINAFLA 2021. 7. 1. 13:00

본문

반응형
  • 액티비티와 같은 컴포넌트는 인텐트에 실행 메시지도 전달하지만 인텐트를 통해 데이터도 주고받을 수 있다.
  • 인텐트 내부에 번들(bundle)이라는 데이터 저장 공간이 있다. 이 공간에 데이터를 담아서 주고받을 수 있다.
 

SubActivity 값 주기

mainActivity.kt 값 추가

        val intent = Intent(this, SubActivity::class.java)
        intent.putExtra("form1", "hello Bundle")
        intent.putExtra("form2", 2020)
 
  • 인텐트에 값을 넣을 때는 키와 값의 조합으로 번들에 직접 넣는다.
  • 꺼낼 때는 처음 입력했던 키로 꺼낸다.
 

activity_sub.xml 값 출력 TextView 추가

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context=".SubActivity">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="서브 액티비티"
        android:textAppearance="@style/TextAppearance.AppCompat.Large" />
    <TextView
        android:id="@+id/to1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="to1"
        android:textAppearance="@style/TextAppearance.AppCompat.Large" />
    <TextView
        android:id="@+id/to2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="to2"
        android:textAppearance="@style/TextAppearance.AppCompat.Large" />
</LinearLayout>
 
 

subActivity.kt 값 가져와서 TextView에 추가하기

to1.text = intent.getStringExtra("form1")
to2.text = "${intent.getIntExtra("form2", 0)}"
 
  • intent는 액티비티의 기본 속성이다. 따라서 전달된 값은 intent로 바로 호출해서 사용할 수 있다.
  • form2의 값은 숫자 값이 입력이 됐기 때문에 getIntExtra() 함수를 사용해서 꺼낸다.
 
 

실행화면

 
 

 

MainActivity 값 전달하기

activity_sub.xml 소스 추가하기

        <EditText
            android:id="@+id/editText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPersonName" />
 
        <Button
            android:id="@+id/btnClose"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="메인에 값 전달하기" />
 

SubActivity.kt 추가하기

    btnClose.setOnClickListener {
            val returnIntent = Intent()
            returnIntent.putExtra("returnValue", editText.text.toString())
            setResult(Activity.RESULT_OK, returnIntent)
            finish()
        }
 
  • SetResult() 메서드에 담아서 실행하면 호출한 측으로 전달된다.
설명
RESULT_OK
처리한 결과 값 성공
RESULT_CANCEL
처리한 결과 값 실패이거나 취소
 

MainActivity.kt 추가하기

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val intent = Intent(this, SubActivity::class.java)
        intent.putExtra("form1", "hello Bundle")
        intent.putExtra("form2", 2020)
 
        btnSub.setOnClickListener {
            startActivityForResult(intent,99)
        }
    }
 
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
 
        if(resultCode == Activity.RESULT_OK) {
            val message = data?.getStringExtra("returnValue")
            Toast.makeText(this, message, Toast.LENGTH_LONG).show()
        }
    }
 
  • 기존에 startActivity() 메서드로 SubActivity를 실행하면 값이 안 온다.
  • startActivity() 함수 말고, startActivityForResult() 함수로 SubActivity 화면을 호출한다.
  • startActivityForResult()  메소드는 SubActivity를 호출한 곳으로 값을 넘겨주는 함수다.
 
 

실행화면

 

반응형

'IT > 기초' 카테고리의 다른 글

[Spring] 어노테이션(Annotaiton)  (0) 2021.08.08
[Dart] 비동기 프로그래밍  (0) 2021.07.02
[Flutter] StatefulWidget의 라이프 사이클  (0) 2021.06.30
Flutter 개발환경 구축 (Windows)  (0) 2021.06.18
웹의 동작 방식  (0) 2021.03.17

관련글 더보기

댓글 영역