How to update the `ListView` according to `ArrayList`?

前端 未结 5 512
傲寒
傲寒 2021-01-29 08:37

I have an array of contacts that I am constantly updating. I want my ListView to update with my contacts.

Should I use an Adapter for that? I

5条回答
  •  旧时难觅i
    2021-01-29 09:21

    Instead of an Array, I recommend using ArrayList.

    The advantage of ArrayList over Array is that arrays require fixed size. So if you are initializing an Array

    String names[] = new String[10];
    

    the size is 10, and when you set to ListView, the ListView will show 10 lists, even though there is name only in 8 array positions

    Where as if you use ArrayList, you don't have to worry about size, since it can scale up and down

    List names = new ArrayList<>();
    names.add("Raul");
    names.add("Khan");
    names.remove(1);
    

    add() adds an item to the list, while remove() removes an item.

    With respect to your answer, say you have an ArrayList of items

    and when you have a new item to add to the list, just add it to your ArrayList with the add() method, and finally call notifyDataSetChanged() on your ArrayAdapter.

    And YES, you have to use an ArrayAdapter like this

    ArrayList namesList = new ArrayList<>();
    ArrayAdapter arrayAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, namesList);
    

    And when you have changes to the list, ie when you add items to your list, call notifyDataSetChanged() on arrayAdapter.


提交回复
热议问题