For Kotlin !!
Custom Array adapter to hide the last item of the spinner
import android.content.Context
import android.widget.ArrayAdapter
import android.widget.Spinner
class HintAdapter<T>(context: Context, resource: Int, objects: Array<T>) :
ArrayAdapter<T>(context, resource, objects) {
override fun getCount(): Int {
val count = super.getCount()
// The last item will be the hint.
return if (count > 0) count - 1 else count
}
}
Spinner Extension function to set hint on spinner
fun Spinner.addHintWithArray(context: Context, stringArrayResId: Int) {
val hintAdapter =
HintAdapter<String>(
context,
android.R.layout.simple_spinner_dropdown_item,
context.resources.getStringArray(stringArrayResId)
)
hintAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
adapter = hintAdapter
setSelection(hintAdapter.count)
}
How to use: add the extension by passing context and array on Spinner
spinnerMonth.addHintWithArray(context, R.array.months)
Note: The hint should be the last item of your string array
<string-array name="months">
<item>Jan</item>
<item>Feb</item>
<item>Mar</item>
<item>Apr</item>
<item>May</item>
<item>Months</item>
</string-array>