안드로이드(Kotlin)/기초/

Spinner(Selector, ComboBox) 사용법 (2)

2020. 4. 22.

파일 구조

Model.kt 추가

 

컴포넌트 트리

Spinner -> id: opt

 

Model 코드

package com.example.myexam1

class Model (val name: String, val price: Int){
    override fun toString(): String {
        return name
    }
}

 

코드

package com.example.myexam1

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(){

    val array = arrayOf(
        Model("사과",2500),
        Model("배",2000),
        Model("포도",5000)
    )

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

        val adapter = ArrayAdapter(this,android.R.layout.simple_spinner_dropdown_item,array)
        opt.adapter = adapter
        opt.onItemSelectedListener = object :AdapterView.OnItemSelectedListener{
            override fun onNothingSelected(parent: AdapterView<*>?) {
                TODO("Not yet implemented")
            }

            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                with(array[position]){
                    textView.text = "${name}의 가격은 ${price}원 입니다"
                }
            }

        }
    }
}