Kotlin spinner selecteditem为null

时间:2018-05-14 04:10:13

标签: android kotlin spinner

我在Kotlin中有一个微调器并使用kotlinx将其导入代码。

这是xml:

中的代码
<Spinner
    android:id="@+id/sp_from_country"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:dropDownSelector="@color/colorPrimary"
    android:spinnerMode="dropdown"/>

这是kotlin中的代码:

this.sp_from_country.adapter = this.adapter
this.sp_from_country.setSelection(0)

这是我使用按钮点击事件的下拉列表

的地方
this.currencyForm = getCurrencyCode(sp_from_country.selectedItem.toString())

问题是selectedItem始终为null。

这是我片段的完整源代码

package training.com.aaptraining.views

import android.app.AlertDialog
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.v4.app.Fragment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import kotlinx.android.synthetic.main.view_fragment_currency.*
import training.com.aaptraining.R
import training.com.aaptraining.viewmodel.CurrencyViewModel

class CurrencyFragment : Fragment() {
companion object {
    fun newInstance() = CurrencyFragment()
}

private val currencies = ArrayList<String>()
private lateinit var currenciesAdapter: ArrayAdapter<String>
private lateinit var currencyForm: String
private lateinit var currencyTo: String

private lateinit var currencyViewModel: CurrencyViewModel
private val spinner: Spinner? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    this.initViewModel()
}

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.view_fragment_currency, container, false)
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    this.initUI()
    this.populateSpinnerAdapter()
}

private fun populateSpinnerAdapter() {
    this.currencyViewModel.loadCurrencyList()
            ?.observe(this, Observer { currencyList ->
                currencyList?.forEach {
                    currencies.add(it.code + " " + it.country)
                }
            })

    this.currenciesAdapter.setDropDownViewResource(R.layout.item_spinner)
    this.currenciesAdapter.notifyDataSetChanged()
}

private fun initUI() {
    this.initSpinners()
    this.initConvertButton()
}

private fun initConvertButton() {
    this.btn_convert.setOnClickListener { this.convert() }
}

private fun convert() {
    val quantity = edt_value.text.toString()
    this.currencyForm = getCurrencyCode(sp_from_country.selectedItem.toString())
    this.currencyTo = getCurrencyCode(sp_to_country.selectedItem.toString())
    val currencies = "$currencyForm,$currencyTo"

    if (quantity.isNotEmpty() && currencyForm != currencyTo) {
        this.currencyViewModel.getAvailableExchange(currencies)
                ?.observe(this, Observer { availableExchange ->
                    availableExchange?.run {
                        exchange(quantity.toDouble(), availableExchangeMap)
                    }
                })
    }
}

private fun exchange(quantity: Double, availableExchangeMaps: Map<String, Double>) {
    val exchangeKeys = availableExchangeMaps.keys.toList()
    val exChangesValues = availableExchangeMaps.values.toList()

    val fromCurrency = exChangesValues[0]
    val toCurrency = exChangesValues[1]

    val fromCurrencyKey = this.getCurrencyCodeResult(exchangeKeys[0])
    val toCurrencyKey = this.getCurrencyCodeResult(exchangeKeys[1])

    val usdExChange = quantity.div(fromCurrency)
    val exchangeResult = usdExChange.times(toCurrency)

    this.showResult(quantity.toString() + " $fromCurrencyKey = " + exchangeResult.format(4)
            + " $toCurrencyKey")
}

private fun showResult(result: String) {
    AlertDialog.Builder(context!!, R.style.AppCompatAlertDialogStyle)
            .setMessage(result)
            .setTitle("You got the result")
            .setCancelable(false)
            .setPositiveButton(android.R.string.ok, null)
            .setIcon(R.drawable.ic_attach_money_black_24dp)
            .create()
            .show()
}

private fun getCurrencyCodeResult(currencyCode: String) = currencyCode.substring(3)

private fun getCurrencyCode(currency: String) = currency.substring(0, 3)

private fun initSpinners() {
    this.currenciesAdapter = ArrayAdapter(activity, R.layout.item_spinner, currencies)
    this.sp_from_country.adapter = this.currenciesAdapter
    this.sp_from_country.setSelection(0)
    this.sp_to_country.adapter = this.currenciesAdapter
    this.sp_to_country.setSelection(0)

    this.sp_from_country?.onItemSelectedListener = object: AdapterView.OnItemSelectedListener {
        override fun onNothingSelected(p0: AdapterView<*>?) {
            Log.d("Currency Framgnet", "On spinner nothing selected")
        }

        override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
            Log.d("Currency Framgnet", "On spinner selected")
        }
    }
}

private fun initViewModel() {
    this.currencyViewModel = ViewModelProviders.of(this).get(CurrencyViewModel::class.java)
    this.currencyViewModel.let { lifecycle.addObserver(it) }
    this.currencyViewModel.initLocalCurrencies()
}

private fun Double.format(digits: Int) = java.lang.String.format("%.${digits}f", this)
}

1 个答案:

答案 0 :(得分:0)

考虑尝试使用此代码段设置微调器,

val arrayAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, monthList)
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner_month.adapter = arrayAdapter

要获取所选项目,请使用此方式,

spinner_month.selectedItem.toString()