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

前端 未结 5 465
傲寒
傲寒 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条回答
  •  北海茫月
    2021-01-29 09:44

    I usually have a method called setData(List data) in my Adapter. My Adapter is let's say in an Activity. When In my activity I obtain an updated array from wherever, I call setData() with the new array containing the updated array.

    In my Adapter I have a field defined like: private List mItems. I use this field in the getCount() method of the Adapter to obtain the list items, basically I use this list to populate the ListView.

    What I do in the setdata() is assign data to mItems and I call notifyDataSetchanged() which refreshes the ListView and this time it will use the newly set data values, so everything updates to the appropriate state.

    UPDATE

    I don't have quick access to an adapter for a ListView but the one below should do, it's for a ViewPager, but the principle is the same:

    public class AdapterTweets extends PagerAdapter {
        private List mItems;
    
        // [...]
    
        @Override
        public int getCount() {
            return mItems == null ? 0 : mItems.size();
        }
    
        // [...]
    
        public void setData(List items) {
            mItems = items;
            notifyDataSetChanged();
        }
    }
    

提交回复
热议问题