how to populate a listview asynchronously?

后端 未结 6 941
说谎
说谎 2020-12-29 07:03

I am wondering how I should implement a ListAdapter that loads its views asynchronously into a ListView? I want to do this because I am populating

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-29 07:40

    You can use an AsyncTask and use the onPostExecute methods to publish the newly loaded results:

    private ArrayAdapter adapter = new YourArrayAdapter();
    
    private class YourAsyncTask extends AsyncTask> {
    
        @Override
        protected void onPreExecute() {
            // start loading animation maybe?
            adapter.clear(); // clear "old" entries (optional)
        }
    
        @Override
        protected List doInBackground(Void... params) {
            // everything in here gets executed in a separate thread
            return DataBase.getItems();
        }
    
        @Override
        protected void onPostExecute(List items) {
            // stop the loading animation or something
            adapter.addAll(items);
        }
    }
    

提交回复
热议问题