initTypeSpinner() {
binding.type.onItemSelectedListener = TypesSpinner()
val ad = ArrayAdapter.createFromResource(this, R.array.types, android.R.layout.simple_spinner_item)
ad.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
binding.type.adapter = ad
}
private fun initMonthSpinner() {
binding.month.onItemSelectedListener = MonthsSpinner()
val adapter = ArrayAdapter.createFromResource(this, R.array.months, android.R.layout.simple_spinner_item)
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
binding.month.adapter = adapter
}
Выбор айтемов каждого из них я обрабатываю в отдельных иннер классах:
inner class TypesSpinner: OnItemSelectedListener {
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
val types = resources.getStringArray(R.array.types)
//Toast.makeText(p1?.context, types[p2], Toast.LENGTH_SHORT).show()
binding.apply {
button.setOnClickListener {
if (energyPrice.text.isNullOrEmpty()) energyPrice.error = getString(R.string.empty_price_error)
if (energyReadings.text.isNullOrEmpty()) energyReadings.error = getString(R.string.empty_readings_error)
}
}
}
override fun onNothingSelected(p0: AdapterView<*>?) {}
}
inner class MonthsSpinner: OnItemSelectedListener {
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
val months = resources.getStringArray(R.array.months)
Toast.makeText(p1?.context, months[p2], Toast.LENGTH_SHORT).show()
}
override fun onNothingSelected(p0: AdapterView<*>?) {}
}
Есть ли возможность обрабатывать выбор айтемов обоих спинеров в одном классе или как-то более лаконично с точки зрения кода?
class MyActivity : AppCompatActivity() { private lateinit var binding: ActivityMyBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMyBinding.inflate(layoutInflater) setContentView(binding.root) initTypeSpinner() initMonthSpinner() binding.type.onItemSelectedListener = object : OnItemSelectedListener { override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) { val types = resources.getStringArray(R.array.types) //Toast.makeText(p1?.context, types[p2], Toast.LENGTH_SHORT).show() binding.apply { button.setOnClickListener { if (energyPrice.text.isNullOrEmpty()) energyPrice.error = getString(R.string.empty_price_error) if (energyReadings.text.isNullOrEmpty()) energyReadings.error = getString(R.string.empty_readings_error) } } } override fun onNothingSelected(p0: AdapterView<*>?) {} } binding.month.onItemSelectedListener = object : OnItemSelectedListener { override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) { val months = resources.getStringArray(R.array.months) Toast.makeText(p1?.context, months[p2], Toast.LENGTH_SHORT).show() } override fun onNothingSelected(p0: AdapterView<*>?) {} } } }
Обсуждают сегодня