Change Spinner's getAdapter() and setAdapter() method
This question seems obvious, but I can't figure it out. I have a custom LanguageSpinner class:
class LanguageSpinner(context: Context, attrs: AttributeSet) : AppCompatSpinner(context, attrs) {
override fun getSelectedItem(): LanguageSpinnerItem {
return super.getSelectedItem() as LanguageSpinnerItem
}
fun getSelectedLanguage() : Language {
return selectedItem.language
}
override fun setAdapter(languageSpinnerAdapter: LanguageSpinnerAdapter) {
this.adapter = languageSpinnerAdapter // ?
}
override fun getAdapter(): LanguageSpinnerAdapter {
return super.getAdapter() // ?
}
}
I need to ensure, that the getSelectedItem()
method will return a Language class object. So my adapter has to be an instance of LanguageSpinnerAdapter
. How can I override getter and setter for the adapter to receive instances of this exact custom adapter? As for now, it says that setter overrides nothing. And I understand, it's due to the fact that LanguageSpinnerAdapter is not SpinnerAdapter, but I've implemented it in my custom adapter. So what can I do?
My custom adapter class:
class LanguageSpinnerAdapter(
context: Context, private val languageItems : ArrayList<LanguageSpinnerItem>
) : ArrayAdapter<LanguageSpinnerItem>(context, R.layout.spinner_item, languageItems),
SpinnerAdapter {
...
}
Does this help?
class LanguageSpinner(context: Context, attrs: AttributeSet) : AppCompatSpinner(context, attrs) {
override fun setAdapter(languageSpinnerAdapter: SpinnerAdapter) {
super.setAdapter((languageSpinnerAdapter as? LanguageSpinnerAdapter) ?: return)
}
override fun getAdapter(): SpinnerAdapter? {
return super.getAdapter() as? LanguageSpinnerAdapter
}
}
I prefer this way of doing null safety but there are also people using let
(languageSpinnerAdapter as? LanguageSpinnerAdapter)?.let {
super.setAdapter(it)
}
By the way you have to use SpinningAdapter otherwise you will not match the base method. That results in a 'method overrides nothing' error.