How to update a spinner dynamically?

后端 未结 10 1160
北荒
北荒 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:04

    Using add/remove on your adapter and using notifyDataSetChanged() enables you not having to create new adapters over and over again.

    Declare your adapter global

    ArrayAdapter adapter;
    
    

    When you add something to the List of Objects the adapter is attached to (Strings or whatever object you use) add an add function to the adapter and call notifyDataSetChanged:

    adaper.add(Object);
    adapter.notifyDataSetChanged();
    

    and when you remove an item from the List add also:

    adapter.remove(Object);
    adapter.notifyDataSetChanged();
    

    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 you can use setNotifyOnChange(true)

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

    提交回复
    热议问题