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

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

2020. 4. 22.

컴포넌트 트리

Spinner -> id: opt

Button1 -> id: addBtn

Button2 -> id: delBtn

 

코드

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.*
import kotlin.random.Random
import kotlin.random.nextInt

class MainActivity : AppCompatActivity(){

    val list = mutableListOf<Int>()

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

        val adapter = ArrayAdapter(this,android.R.layout.simple_spinner_dropdown_item,list)

        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.text = "${list[position]}을 선택하였습니다"
            }

        }

        addBtn.setOnClickListener {
            list.add(Random.nextInt(0..100))
            adapter.notifyDataSetChanged()
        }

        delBtn.setOnClickListener {
            if(list.size > 1){
                list.removeAt(0)
                adapter.notifyDataSetChanged()
            }
        }
    }
}