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?

More than 1 year has passed since last update.

[Android] [Kotlin] Spinnerの初期値項目を文字列で選択する方法

Posted at

はじめに

spinnerの初期値項目を設定するときにsetSelectionを使いますが、この引数は(position: Int)となっていて
ちょっとめんどくさいと思いました。
setTextみたいに入れて自動的にリストにある同名の項目を初期値設定にしたい方におすすめです。
javaでの方法があったので、kotlinにしてあげたものです。

.kt
val spinner: Spinner = findViewById(R.id.spinner)
spinner.setSelection(setSelection(spinner, "文字列"))

private fun setSelection(spinner: Spinner, item: String): Int {
        val adapter = spinner.adapter
        var index = 0
        for (i in 0  until < adapter.count) {
            if (adapter.getItem(i) == item) {
                index = i
            }
        }
        return index
    }

"文字列"の部分で自動検索し、同名の項目をSpinnerの初期値として表示します。
試してみてください!

参考記事
http://anadreline.blogspot.com/2013/07/spinner.html

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?