I have a project using 2 dropdowns. First one is for Buildings The second is for apartment number inside building. So when we select A building and apartment number, we get the Owner name.
I have created lists in strings.xml
<!-- LIST buildings-->
<string-array name="list_buildings">
<item>Building 1</item>
<item>Building 3</item>
<item>Building 3</item>
</string-array>
<!-- LIST Houses-->
<string-array name="list_houses">
<item>House 1</item>
<item>House 2</item>
<item>House 3</item>
</string-array>
I have tried this in MainActivity.kt
// buildings
// list in strings.xml
val buildings = resources.getStringArray(R.array.list_buidings)
val buldingAdapter = ArrayAdapter(
this,
R.layout.dropdown_buildings,
buildings
)
// Houses
val houses = resources.getStringArray(R.array.list_houses)
val houseAdapter = ArrayAdapter(
this,
R.layout.dropdown_llamadas,
houses
)
// ▼ id from AutoCompleteTextViews
// in activity_main.xml
with(binding.chooseBuilding) {
setAdapter(arrayAdapter)
onItemClickListener = this@MainActivity
}
/
with(binding.chooseHouse) {
setAdapter(houseAdapter)
// LISTENERS
onItemClickListener = this@MainActivity
}
}
override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
val item = parent?.getItemAtPosition(position).toString()
// this is to test if dropdowns are working. OK
// the problem is I can´t separate both dropdowns
Toast.makeText(this@MainActivity, item, Toast.LENGTH_SHORT).show()
// I get error trying to change the "item" element to customize the logic.
if ( (item == "Building 1") || (item == "House 2" ) && (binding.chooseBuilding.isSelected)) {
binding.myTextView.text = "Katerine lives here..."
}
Thanks for your help
First, if you are using Spinner then you should use onItemSelectedListener
instead of onItemClickListener
onItemSelectedListener = this@MainActivity
Second, you can separate both dropdowns simply by using the parent
variable from the override function like this:
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
var building = ""
var houses = ""
if (parent == binding.chooseBuilding) {
building = parent.getItemAtPosition(position).toString()
} else if (parent == binding.chooseHouse) {
houses = parent.getItemAtPosition(position).toString()
}
if ((building == "Building 1") || (houses == "House 2") && (binding.chooseBuilding.isSelected)) {
Log.d("TAG", "Katerine lives here...")
}
}