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

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

2020. 4. 22.

컴포넌트 트리

Spinner -> id: opt

 

코드

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

    var array = arrayOf("사과","딸기","바나나","배","포도")

    var adapter: ArrayAdapter<String>? = null

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

        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
            ) {
                textView.setText("${array[position]}을(를) 선택하였습니다")
            }

        }
    }
}