How to update a spinner dynamically?

后端 未结 10 1182
北荒
北荒 2020-12-08 02:32

I\'ve been trying to update my spinner in android dynamically but nothing I try has been working.

This is the following code I\'m using to update the spinner.

10条回答
  •  醉酒成梦
    2020-12-08 03:00

    You can't directly modify the original List then call notifyDataSetChanged() like on other adapters, as it doesn't hold on to the original List.

    You can, however, achieve the same result using the adapter itself, like so:

    spinnerAdapter.clear();
    spinnerAdapter.addAll(updatedListData);
    spinnerAdapter.notifyDataSetChanged(); // optional, as the dataset change should trigger this by default
    

    Based on this answer from user392117.

    edit: By default, methods that change the list like add() and remove() automatically call notifyDataSetChanged() (see Android Developer Documentation for setNotifyOnChange(boolean) )

    public void setNotifyOnChange (boolean notifyOnChange)

    Control whether methods that change the list (add, addAll(java.util.Collection), addAll(java.lang.Object[]), insert, remove, clear, sort(java.util.Comparator)) automatically call notifyDataSetChanged. If set to false, caller must manually call notifyDataSetChanged() to have the changes reflected in the attached view. The default is true, and calling notifyDataSetChanged() resets the flag to true.

    So you should not need to call notifyDataSetChanged() every time. If you find that this is the case, you can use setNotifyOnChange(true)

    spinnerAdapter.setNotifyOnChange(true); //only need to call this once
    spinnerAdapter.add(Object); //no need to call notifyDataSetChanged()
    

提交回复
热议问题