How to set dropdown menu string array according to another dropdown menu (Android)?

Viewed 18

I have 2 dropdown menus(1 -> autoCompleteTextProductType 2-> autoCompleteTextProductBrand)

I need to get the value of product type(it's a String like: Mobile Phones, Computers etc.) from autoCompleteTextProductTypeand according to that value I need to change the resources of autoCompleteTextProductBrand For example if the chosen product type is = Mobile Phones then autoCompleteTextProductBrand resources would set to phone brands (Samsung Apple etc.) I tried something like this:

    //ProductTypeDropDownMenu
    val productTypes = resources.getStringArray(R.array.productTypes)
    val productArrayAdapter = ArrayAdapter(requireActivity(),R.layout.dropdown_item,productTypes)
    autoCompleteTextProductType.setAdapter(productArrayAdapter)
    
    //if autoCompleteTextProductBrand dropdown menu clicked get the right brand array. 
    //Then use the brand array for brand adapter

    autoCompleteTextProductBrand.setOnClickListener{
        val type = autoCompleteTextProductType.text.toString()
        val brands = returnProductBrandArray(type)
        val brandAdapter = ArrayAdapter(requireActivity(),R.layout.dropdown_item,brands)
        autoCompleteTextProductBrand.setAdapter(brandAdapter)
    }

    //This function is for getting the right string array. It needs a type. And returns 
    //string array directly.

    private fun returnProductBrandArray(type: String) : Array<String>{
        val brands = if(type == "Mobile Phones"){
           resources.getStringArray(R.array.phoneBrands)
           }
           else{
                resources.getStringArray(R.array.computerBrands)
           }

       return brands
}

The issue in this solution is that when I click on dropdown menu first, no values are showing up. (I think that's because I created the adapter inside the onclick listener) But for the second time I click on it datas are showing up correctly. How can I solve this problem? I hope I summarized the issue well.

0 Answers
Related