반응형

Spinner의 onItemSelectedListener에 AdapterView.OnitemSelectedListener 람다식을 대입하는 방법은

Object 객체를 만들어서 onItemSelected, onNothingSelected 을 오버라이딩하면 됩니다.

spinner1.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                ivPoster.setImageResource(posterID[position])
            }
 
            override fun onNothingSelected(parent: AdapterView<*>?) {
            }
 

 

[Gradle 설정]

1
id 'kotlin-android-extensions'
cs

<MainActivity>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.cookandroid.project11_3
 
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import kotlinx.android.synthetic.main.activity_main.*
 
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "스피너 테스트"
 
        var movie = arrayOf(
            "영화 제목1", "영화 제목2", "영화 제목3", "영화 제목4",
            "영화 제목5", "영화 제목6", "영화 제목7", "영화 제목8",
            "영화 제목9", "영화 제목10"
        )
 
        var posterID = arrayOf(
            R.drawable.mov01, R.drawable.mov02, R.drawable.mov03, R.drawable.mov04,
            R.drawable.mov05, R.drawable.mov06, R.drawable.mov07, R.drawable.mov08,
            R.drawable.mov09, R.drawable.mov10,
        )
 
        var adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, movie)
        spinner1.adapter = adapter
        spinner1.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                ivPoster.setImageResource(posterID[position])
            }
 
            override fun onNothingSelected(parent: AdapterView<*>?) {
            }
 
        }
    }
}
cs

<activity_main.xml>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
 
    <Spinner
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/spinner1"/>
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="10dp"
        android:id="@+id/ivPoster"/>
 
</LinearLayout>
cs
반응형

+ Recent posts