Last active
July 10, 2022 11:00
-
-
Save milhauscz/e227680bebc498d0e41f8dc7c164a155 to your computer and use it in GitHub Desktop.
Custom adapter for MaterialSpinner
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Custom adapter for [MaterialSpinner]. Just implement [getView] to provide the given View, e. g. | |
* by using [inflater]. In case of data binding, the binding object can be set as the given View's | |
* tag to be able to retrieve it when reusing the given View and implement custom viewholder pattern. | |
* [selectedItemPosition] can be used for updating the selected View's UI. When used together with | |
* [MaterialSpinner], [selectedItemPosition] is updated automatically and [notifyDataSetChanged] is called. | |
* | |
* Created by Milos Cernilovsky on 4/21/21 | |
*/ | |
abstract class MaterialSpinnerAdapter<T>(context: Context, private val objects: List<T>) : BaseAdapter(), Filterable { | |
// fake filter to implement Filterable (required by MaterialSpinner's AutocompleteTextView parent) | |
private val _filter: Filter by lazy { | |
object : Filter() { | |
override fun performFiltering(constraint: CharSequence?): FilterResults { | |
return FilterResults() | |
} | |
override fun publishResults(constraint: CharSequence?, results: FilterResults?) { | |
} | |
} | |
} | |
val inflater: LayoutInflater = LayoutInflater.from(context) | |
var selectedItemPosition = 0 | |
set(value) { | |
field = value | |
notifyDataSetChanged() | |
} | |
override fun getCount(): Int = objects.size | |
override fun getItem(position: Int): T = objects[position] | |
override fun getItemId(position: Int): Long = position.toLong() | |
override fun getFilter(): Filter = _filter | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I am receiving the following error when initialising the adapter:
Your example code lacks implementation example:
I initialise the adapter in
onCreate
function of activity:Can you give some pointers?