Skip to content

Instantly share code, notes, and snippets.

@CapnSpellcheck
Last active February 21, 2018 02:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CapnSpellcheck/9d2f91b3590144d4f50ce5b5d6079c75 to your computer and use it in GitHub Desktop.
Save CapnSpellcheck/9d2f91b3590144d4f50ce5b5d6079c75 to your computer and use it in GitHub Desktop.
Adapter extending BaseAdapter on Android to show a Spinner based on Enum. The Enum class should also implement Displayable.
/**
* If isOptional, then position 0 is a "No response" item.
*/
class EnumAdapter<DispEnum>(val context: Context, enumClass: Class<DispEnum>,
@IntegerRes var resource: Int = android.R.layout.simple_spinner_item,
@IntegerRes var dropDownResource: Int = android.R.layout.simple_spinner_dropdown_item,
val isOptional: Boolean = false) :
BaseAdapter() where DispEnum : Displayable, DispEnum : Enum<DispEnum>
{
val inflater: LayoutInflater = LayoutInflater.from(context)
val konstants: Array<DispEnum> = enumClass.enumConstants
override fun getItem(position: Int): Displayable {
if (isOptional) {
return if (position == 0) NoResponseDisplayable else konstants[position - 1]
}
return konstants[position]
}
override fun getItemId(position: Int): Long = position + 0L
override fun getCount(): Int = konstants.size + if (isOptional) 1 else 0
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
return createViewFromResource(position, convertView, parent, resource)
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
return createViewFromResource(position, convertView, parent, dropDownResource)
}
private fun createViewFromResource(position: Int, convertView: View?, parent: ViewGroup, resource: Int): View {
val view = convertView ?: inflater.inflate(resource, parent, false)
val textView: TextView
try {
textView = view as TextView
} catch (e: ClassCastException) {
Log.e("EnumAdapter", "You must supply a resource ID for a TextView")
return view
}
val displayable = getItem(position)
textView.text = displayable.displayString(context.resources)
return view
}
}
private object NoResponseDisplayable : Displayable {
override fun displayString(res: Resources): String = res.getString(R.string.no_response)
}
interface Displayable {
fun displayString(res: Resources): CharSequence = res.getString(resID)
val resID: Int
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment