코틀린

[코틀린] 문제: Kotlin study 04 / The 친절한 코틀린 앱 프로그래밍

edit0 2021. 3. 7. 23:43
  • 텍스트뷰 1개, 이미지뷰 2개를 추가하고 각각 다른 사진을 보여준다.
  • Singer 클래스를 만들고 그 안에 name, age 속성을 추가
  • Singer 클래스로부터 2 개의 인스턴스 객체를 만들고 첫 번째 Singer 객체는 첫 번째 이미지뷰, 두 번째 Singer 객체는 두 번째 이미지뷰와 일치되도록 한다.
  • 각각의 이미지를 터치하면 가수의 이름을 토스트 메시지로 보여주고 텍스트뷰에도 표시

 

activity_main.xml

<?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"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="선택된 가수: "
        android:id="@+id/tv1"
        android:textSize="30dp"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageView
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/iv1"
            android:src="@drawable/singer1"/>

        <ImageView
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/iv2"
            android:src="@drawable/singer2"/>

    </LinearLayout>

</LinearLayout>

 

Singer.kt

class Singer {

    var name:String? = null
    var age:Int? = null

    constructor(name:String?, age:Int?){
        this.name = name
        this.age = age
    }

}

 

MainActivity.kt

class MainActivity : AppCompatActivity() {

    var singer1:Singer? = null
    var singer2:Singer? = null

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

        singer1 = Singer("조용필", 50)
        singer2 = Singer("이미자", 60)

        iv1.setOnClickListener{
            tv1.setText("선택된 가수: ${singer2?.name}")
            Toast.makeText(applicationContext, "가수 ${singer2?.name}이 선택됨", Toast.LENGTH_LONG).show()
        }

        iv2.setOnClickListener{
            tv1.setText("선택된 가수: ${singer1?.name}")
            Toast.makeText(applicationContext, "가수 ${singer1?.name}이 선택됨", Toast.LENGTH_LONG).show()
        }

    }
}

 

결과