728x90
Intent는 직역하면 요구사항, 의도, 요청사항, 등으로 해석할 수 있으며 안드로이드 컴포넌트들 간에 데이터를 전달하거나, 특정 작업(예: 다른 액티비티 시작)을 실행하는데 사용되는 메시징 객체이다
Intent를 사용하는 대상, 즉 요청을 주고 받는 대상은 아래와 같다.
- Activity와 Activity
- Android System과 내 App (전화, 카메라, 등)
- 다른 App과 내 App (배달앱에서 결제 요청 → 카카오 앱 실행) : 상호간의 합의가 필요
요청의 종류는 '전달만 하는 요청'과 '리턴을 받는 요청'으로 분류 할 수 있다.
Intent를 사용하기 위해선 먼저 Intent객체를 생성해야 하며, 상황에 맞는 생성자를 호출하면 된다.
다음은 Intent를 사용하여 Activity를 전환하는 예시이다.
[MainActivity.kt]
package com.example.androidstudy
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main) //화면을 그려주는 부분(해당 레이아웃으로 화면을그려주겠다)
var change_activity : Button = findViewById(R.id.button)
/*
Intent : 의도, 요구사항, 의사전달, 요청
누구가 누구에게 요청을 하는가?
대상 : Activity 와 Activity, Android 시스템과 내 App(카메라 실행,등), 외부 App과 내 App
요청의 종류 : 전달만 하는 요청, 리턴 받는 요청
*/
change_activity.setOnClickListener{
//0. Intent 생성(요청 생성)
//1. 현재 앱의 Context와 이동할 엑티비티의 클래스
//MainActivity에서 Activity2로 이동하겠다는 의미를 가진 Intent
val intent = Intent(this@MainActivity,Activity2::class.java)
startActivity(intent) //요청 보내기
}
}
}
[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">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="154dp"
android:layout_marginTop="148dp"
android:layout_marginEnd="166dp"
android:layout_marginBottom="535dp"
android:text="인텐트"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
[MainActivity 화면]

[activity_2.xml]
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/black"
tools:context=".Activity2">
</androidx.constraintlayout.widget.ConstraintLayout>
[Activity2 화면]

버튼을 누르면 아래와 같이 잘 이동하는 것을 확인 할 수 있다.
해당 게시글은 패스트 캠퍼트 은창현 강사님의 ⟪Android 앱 개발 올인원 패키지⟫ 를 토대로 작성하였습니다.
'Android' 카테고리의 다른 글
안드로이드 로컬 서버 연동 (0) | 2024.04.24 |
---|---|
[Android] TextView에 폰트 적용하기 (0) | 2023.09.12 |
[Android] Intent(2) : 전달만 하는 요청 (0) | 2023.08.27 |
[Android] Acticity - Life Cycle (0) | 2023.08.25 |
[Android] 프래그먼트 뷰 캡처해서 이미지로 저장하기 (0) | 2023.08.17 |