Skip to content

Instantly share code, notes, and snippets.

@CapnSpellcheck
Created January 26, 2017 00:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CapnSpellcheck/2a46d977b28e03e751f982f52af5f7d5 to your computer and use it in GitHub Desktop.
Save CapnSpellcheck/2a46d977b28e03e751f982f52af5f7d5 to your computer and use it in GitHub Desktop.
IntRangeAdapter: A BaseAdapter that allows for easy handling of an integer range. Allows the minimum or maximum to be changed at any time more easily and efficiently than an ArrayAdapter can.
import android.content.Context
import android.support.annotation.IntegerRes
import android.util.Log
import android.view.*
import android.widget.BaseAdapter
import android.widget.TextView
class IntRangeAdapter(val context: Context,
@IntegerRes var resource: Int,
@IntegerRes var dropDownResource: Int,
minInclusive_: Int,
maxInclusive_: Int)
: BaseAdapter()
{
var minInclusive = minInclusive_
set(value) {
field = value
notifyDataSetChanged()
}
var maxInclusive = maxInclusive_
set(value) {
field = value
notifyDataSetChanged()
}
val inflater: LayoutInflater = LayoutInflater.from(context)
val originalMin: Int
val originalMax: Int
init {
originalMax = maxInclusive_
originalMin = minInclusive_
}
override fun getItem(position: Int): Int = minInclusive + position
override fun hasStableIds(): Boolean = true
override fun getItemId(position: Int): Long = minInclusive.toLong() + position
override fun getCount(): Int = maxInclusive - minInclusive + 1
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)
}
fun getPosition(value: Int): Int {
if (value < minInclusive || value > maxInclusive)
throw IllegalArgumentException("value $value not in range of adapter [$minInclusive, $maxInclusive]")
return value - minInclusive
}
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("IntRangeAdapter", "You must supply a resource ID for a TextView")
return view
}
val item = getItem(position)
textView.text = item.toString()
return view
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment