반응형

Spinner

설명

  • 사용자에게 항목을 선택할 수 있게 제공하는 View
  • HTML의 select 같은 역할
  • ListView처럼 AdpaterView를 활용

코드

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>
class MainActivity : AppCompatActivity() {
    var spinner: Spinner? = null
    val data = arrayOf("스피너1", "스피너2", "스피너3")

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

        val listener = SpinnerListener()

        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, data)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)

        spinner = findViewById(R.id.spinner)
        spinner?.adapter = adapter
        spinner?.onItemSelectedListener = listener
    }

    inner class SpinnerListener : AdapterView.OnItemSelectedListener {
        override fun onNothingSelected(parent: AdapterView<*>?) {
            TODO("Not yet implemented")
        }

        override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
            Toast.makeText(baseContext, data[position] + " / " + spinner?.selectedItem, Toast.LENGTH_SHORT).show()
        }
    }
}

참고

반응형

'Development > Android' 카테고리의 다른 글

[Android] RecyclerView  (0) 2021.02.09
[Android] ViewPager  (0) 2021.02.09
[Android] ListView  (0) 2021.02.09
[Android] Layout  (0) 2021.02.09
[Android] View  (0) 2021.02.09

+ Recent posts