I have an ExposedDropdownMenu implemented in my app, and while hamfisted, it gets the job done and I'm able to style it how I want it to look. On my country "spinner", i want the list of states to change to provinces if canada is selected, then be populated with a list of canadian provinces. When my "spinner" was an actual Spinner
, OnItemSelectedListener
worked flawlessly, however, it no longer is changing back and forth now that I've implemented the "spinner" as an EDM
Here is my code:
// get country spinner values and change state/zip options depending on country selected
val countryAdapter = MaterialSpinnerAdapter<String>(it, R.layout.material_spinner_item, it.resources.getStringArray(R.array.country))
country_dropdown.setAdapter(countryAdapter)
country_dropdown.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
displayStatesForSelectedCountry(position)
}
override fun onNothingSelected(parent: AdapterView<*>?) {
displayDefaultStatesList()
}
}
private fun displayStatesForSelectedCountry(position: Int) {
context?.let {
val canadaAdapter = MaterialSpinnerAdapter<String>(it, R.layout.material_spinner_item, it.resources.getStringArray(R.array.states_of_canada))
when(position) {
1 -> {
displayDefaultStatesList()
}
2 -> {
state_dropdown.setAdapter(canadaAdapter)
enrollment_zip_code.hint = it.resources.getString(R.string.enrollment_hint_postal_code)
enrollment_zip_code.editText?.inputType = InputType.TYPE_CLASS_TEXT
}
else -> displayDefaultStatesList()
}
}
}
Thinking that maybe the behaviour has changed, I attempted to implement the OnItemClickedListener
instead:
country_dropdown.setOnItemClickListener { parent: AdapterView<*>?,
view: View?,position:
Int,id: Long ->
displayStatesForSelectedCountry(position)
}
No dice. I know that the listener(s) are not being called at all because at the very least, the zipcode hint would change to postal code, however, it does not. What am I doing wrong here? should I not be using the position? if not, why not? MaterialSpinnerAdapter
is just a subclass of ArrayAdapter
to prevent filtering when I dont want it to filter, but i should be able to reliably use the position to determine what to show.
It occurred to me that its a type of EditText
, so this works:
country_dropdown.addTextChangedListener(object: TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(
s: CharSequence?,
start: Int,
count: Int,
after: Int
) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
displayStatesForSelectedCountry(s.toString())
viewModel.country.value = s.toString()
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With