0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Spinnerの使い方

0
Posted at

AndroidのSpinner使い方をメモします。これは複数の選択肢から1つを選択するためのUIです。

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

ArrayAdapterを使用して選択肢を設定します。

val items = listOf("東京", "大阪", "名古屋", "福岡")

val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, items).apply {
    // 選択肢一覧のレイアウトを設定する
    setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
}
binding.spinner.adapter = adapter

setSelection()を使うと、指定した位置の項目を選択できます。

// 2番目の大阪をセットする
binding.spinner.setSelection(1)

現在選択されている項目は、selectedItemで取得できます。

val selectedItem = binding.spinner.selectedItem.toString()

選択が変更されたときに処理を実行するには、onItemSelectedListenerを使用します。

binding.spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {

    override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
        // 選択したタイミングで都道府県を取得する。
        val selectedItem = parent.getItemAtPosition(position).toString()
    }

    override fun onNothingSelected(parent: AdapterView<*>) {}
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?