Android Application

Kotlin when 문

작성자 임베디드코리아 작성일23-08-27 19:37 조회1,849회 댓글0건

첨부파일

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

        //텍스트뷰 초기화
        var textView : TextView = findViewById(R.id.textView);

        var color : Int = 12;

        //1. 조건문 통해 변수에 담기

        var word : String = when(color){

            //color값이 0 ~ 5에 해당되면
            in 0..5 -> "Red"

            //0 ~ 11에 해당되면
            in 0..11 -> "Blue"

            //12에 해당되면
            12 -> "Green"

            //위에 경우가 다 아닌경우
            else -> "Yello"
        }
        textView.append("1. 조건문 통해 변수에 담기 \n")
        textView.append("\t\t\t word + \n");

        //2. 조건문 통해 코드 실행
        textView.append("\n2. 조건문 통해 코드 실행 \n")

        when(color){

            in 0..5 -> textView.append("0 ~ 5 \n")
            in 0..11 -> textView.append("0 ~ 11 \n")
            12,13 -> textView.append("\t\t\t 12, 13 \n")

            else -> textView.append("\t\t\t else \n")
        }

        textView.append("\n ------------------- \n")
        val value = 2

        val result = when (value) {
            1 -> "첫번쨰"
            2 -> "두번쨰"
            3 -> "세번쨰"
            4 -> "네번째"
            else -> "기타"
        }
        textView.append("$result  \n")
    }
}

----------------------------------------------------------------------------------------
    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:textSize="25sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>