Счетчик Kotlin выбранный элемент является нулевым - PullRequest
0 голосов
/ 14 мая 2018

У меня есть счетчик в 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())

Проблема выбрана. Элемент всегда равен нулю.

Это полный исходный код моего фрагмента

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 голосов
/ 14 мая 2018

Попробуйте использовать этот фрагмент кода для установки счетчика,

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()
...