Android App/Kotlin

Activity(액티비티 사이에 값 주고받기)-Intent사용

AppJinny 2022. 11. 9. 02:01

*Activity(액티비티 사이에 값 주고받기)-Intent사용

-인텐트 내부 번들(bundle)이라는 데이터 저장공간을 사용해 데이터를 담아서 주고받을 수 있음

-인텐트 값 입력 시 키 값, 값의 조합으로 입력

-인텐트 값 꺼낼 시 키 값으로 꺼냄

-putExtra("키 값", "전달할 값") : 인텐트에 값 전달, 여러 타입의 값을 전달할 수 있도록 오버로드 되어있음

-getStringExtra("키 값") : 인텐트에 담겨온 값 가져오기, 문자열을 꺼냄

-getIntExtra("키 값", 0) : 인텐트에 담겨온 값 가져오기, 숫자 값을 꺼냄, 두 번째 파라미터 값은 아무런 값도 전달되지 않았을 경우 디폴트로 사용할 기본값 설정

--getIntExtra()를 텍스트뷰의 text값에 사용 시 문자열 템플릿 "${}"를 사용하여 문자열로 변환필요

 

[메인 엑티비티]

-activity_main.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"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:text="Main Activity"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sub Activity Start"
        android:layout_marginTop="24dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

-build.gradle

-- android{} 에 뷰바인딩 추가

//뷰바인딩
buildFeatures{
    viewBinding true
}

 

-MainActivity.kt

class MainActivity : AppCompatActivity() {

    //뷰바인딩
    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)

        //putExtra() 메서드 사용 : 인텐트에 값 전달
        //2개의 파라미터 : (키, 값)
        //값을 담을 때 타입구분이 없지만 꺼낼 때는 값의 타입을 구분함
        intent.putExtra("from1","Hello Bundle")
        intent.putExtra("from2",2022)

        //activity_sub.xml에 전달받은 값을 출력할 텍스트뷰 2개 생성
        //SubActivity.kt에 인텐트에 담겨온 값 꺼내서 입력하는 코드 작성

        //버튼을 클릭하면 인텐트 실행
        binding.btnStart.setOnClickListener { startActivity(intent) }

    }
}

 

[서브 엑티비티]

-activity_sub.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"
    tools:context=".SubActivity">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:text="Sub Activity"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

<!--  전달받은 값 출력 뷰  -->
    <TextView
        android:id="@+id/to1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="to1"
        android:layout_marginTop="20dp"
        android:layout_marginStart="50dp"
        app:layout_constraintEnd_toEndOf="@+id/to2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />
    <TextView
        android:id="@+id/to2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="to2"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="50dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/to1"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

-SubActivity.kt

class SubActivity : AppCompatActivity() {

    //뷰바인딩
    val binding by lazy { ActivitySubBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //뷰바인딩
        setContentView(binding.root)

        //텍스트와 뷰를 연결하여 그 텍스트에 인텐트로 담아온 값으로 작성

        //아이디를 사용하여 텍스트뷰의 텍스트를 인텐트로 가져온 값으로 변경
        //인텐트가 가져오는 값은 키 값을 사용하여 입력

        //아이디 to1에 가져온 값이 문자열 이기에 getStringExtra()메서드 사용
        binding.to1.text = intent.getStringExtra("from1")

        //아이디 to2에 가져온 값이 숫자 이기에 getIntExtra()메서드 사용
        //getIntExtra()메서드 두 번째 파라미터 : 아무런 값도 전달되지 않았을 경우 디폴트로 사용할 기본 값
        //텍스트뷰의 text속성은 문자열만 받을 수 있어서 숫자 값을 받을 때
        //문자열 템플릿 사용 : "{$()}"
        binding.to2.text = "${intent.getIntExtra("from2",0)}"

    }
}

 

-결과

 

 

*참고

https://developer.android.com/guide/components/intents-filters?hl=ko

 

인텐트 및 인텐트 필터  |  Android 개발자  |  Android Developers

An Intent is a messaging object you can use to request an action from another app component . Although intents facilitate communication between components in several ways, there are three fundamental use cases: An Activity represents a single screen in…

developer.android.com

 

 

 

 


이 포스팅에 작성한 내용은 고돈호, ⌜이것이 안드로이드다⌟, 한빛미디어(주), 2022 에서 발췌하였습니다.