Develop/Kotlin

[kotlin] 코틀린 액티비티간 화면 전환

JunJangE 2020. 8. 27. 14:18

코틀린에서 액티비티간 화면 전환에 대해 알아보도록 하겠습니다.

코틀린에서 Activity 간 화면 전환을 위해서는 Intent라는 클래스를 사용해야 합니다.

'Intent'는 일종의 메시지 객체라고 이해해주시면 됩니다.

그러면 버튼을 눌렀을 때 다른 액티비티로 전환하는 것을 예제 코드를 통해 알아보도록 하겠습니다.

우선, 버튼을 눌렀을 때 화면 전환이 될 Activity 하나를 생성하도록 하겠습니다.

왼쪽 상단에 File을 눌러 -> New -> Activity -> Empty Activity 순으로 클릭해줍니다.

Empty Activity를 누르게 되면 새로운 Empty Activity 생성되기 전 구성을 도와주는 창이 뜨게 됩니다.

여기서 따로 구성을 바꿀 필요는 없지만 Activity Name은 자신이 봤을 때 알기 쉽게 설정해야 합니다.

위 이미지처럼 저는 "TransformActivity"로 Activity Name을 만들었습니다.

이렇게 화면 전환이 될 Activity를 하나 만들면 준비가 끝납니다.

이제 코드적인 부분으로 넘어가도록 하겠습니다.

MainActivity 레이아웃에다가 버튼을 하나 만들고 버튼의 id를 지정해주겠습니다. 

<?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:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
        
</androidx.constraintlayout.widget.ConstraintLayout>

위 코드에서는 버튼의 id를 "button"으로 지정했습니다.

다음으로 MainActivity로 넘어와 버튼을 눌렀을 때 화면이 전환되는 코드를 구현해보도록 하겠습니다.

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        button.setOnClickListener {
            startActivity(Intent(this@MainActivity,TransformActivity::class.java))

        }
    }
}

위 코드를 보게 되면 button의 '클릭 이벤트 리스너'(setOnClickListener) 안에 있는 Intent로 TransformActivity를 타깃으로 지정하고 startActivity로 실행하여 MainActivity에서 TransformActivity로 화면을 전환시킬 수 있습니다.

 

01

결과 화면을 보게 되면 버튼을 눌렀을 때 TransformActivity로 화면이 전환되는 것을 확인할 수 있습니다.