Android Kotlin - How to set Spinner selected item

a 夏天 提交于 2021-01-27 22:15:42

问题


I have a spinner populated with array of strings from XML:

<Spinner
                android:id="@+id/spinnerUnits"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:entries="@array/units"
                app:layout_constraintStart_toEndOf="@+id/barrier3"
                app:layout_constraintTop_toBottomOf="@+id/labelGeneric" />

When user selects something, I save it to SharedPreferences. How do I set the value back when the app is opened next time? I have only the value saved, not its position in spinner's list.´

If I just do spinner.Units.adapter to get the adapter, how does one safely cast SpinnerAdapter! to ArrayAdapter? Or is this wrong approach?


回答1:


Well you need to post the adapter code as well but here I am giving a sample how I will do in adapter.

 val adapterGender = ArrayAdapter<String>(context, layoutCode, context.resources.getStringArray(R.array.genderArray))

 override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
        val data = listOfItems[holder!!.adapterPosition]
        holder.etName?.setText(data.name)
        holder.spGender?.adapter = adapterGender
        holder.spGender?.setSelection(adapterGender.getPosition(data.gender))
    }

{
        val etName: AppCompatEditText? = itemView?.findViewById(R.id.etName)
        val spGender: AppCompatSpinner? = itemView?.findViewById(R.id.spGender)

        init {
            //listener for gender selection
            spGender?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onNothingSelected(p0: AdapterView<*>?) {

                }

                override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
                    listOfItems[adapterPosition].gender = p0?.selectedItem.toString()
                    Log.d("TAG", p0?.selectedItem.toString())
                }
            }

        }
    }

so basically I am setting a onItemSelectedListener on spinner and listening for value changes and then setting it in model/pojo for persisting and assigning in onBindViewHolder for setting back values.



来源:https://stackoverflow.com/questions/50314977/android-kotlin-how-to-set-spinner-selected-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!