Search code examples
androidkotlinandroid-alertdialog

Adding items to an existing AlertDialog


So I need to show an AlertDialog with one item, then execute a get request, after it's resolved, I need to add more items to the dialog.

I tried the below code without success

var list = arrayOf("aa")
val b = AlertDialog.Builder(context)
b.setItems(list, onItemClickListener)
val dialog = b.create()

executeGetRequest() {
   list += "New Item"
   val adapter = dialog.listView.adapter as ArrayAdapter<*>
   adapter.notifyDataSetChanged()
}

However, updating the existing item is working:

list[0] = "Updated Item"
adapter.notifyDataSetChanged()

What am I missing?


Solution

  • Solved

    val list = arrayListOf("aa")
    val b = AlertDialog.Builder(context)
    val onItemClickListener = DialogInterface.OnClickListener { dialog, which ->
        // code
    }
    val adapter = ArrayAdapter(requireContext(), 
        android.R.layout.simple_list_item_1, list)
    setAdapter(adapter, onItemClickListener)
    
    executeGetRequest() {
       list.add("New Item")
       adapter.notifyDataSetChanged()
    }
    b.show()