Dynamically add items to list view using custom adapter for Android app

℡╲_俬逩灬. 提交于 2019-12-03 23:37:18
LordRaydenMK
  1. In your adapter change the Locations data[] from array to ArrayList<Location> and override the appropriate constructor
  2. In your activity, make your variable data a field (type ArrayList<Location>)
  3. When you add a location you can use data.add(location)
  4. Then you can call notifyDatasetChanged() on your adapter

Example code.

Store your data in an ArrayList<Location> instead of just Location[], and then make a public class in your list adapter:

ArrayList<Location> data = new ArrayList<Location>();

@Override
public void add(Location location) {
    data.add(location);
    notifyDataSetChanged();
}

Then, when you want to add an item to the list, just call location_data.add(new_location).

Edit: It looks like you have your pick from several mostly identical answers.

Looks like you need to override the add method in your LocationAdapter class to add the object to the internal list

@Override
public void add(Location location)
{
    super.add(location);
    data.add(location);
}

This implementation requires that you change data to an ArrayList instead of just an array, otherwise you would have to code the array re-sizing yourself.

ArrayList<Location> data = null; // Alternatively use new ArrayList<Location>();

If you don't do this, the internal data will remain unchanged and a call to add will do not change the list. This is bad because you use the data variable to get the values for the views.

In your main activity, I'd recommend using an ArrayList< Location > rather than Location[] to make it easier to add new Location elements. Then, rather than having LocationAdapter extend ArrayAdapter< Location >, have it extend ListAdapter< Location > so you can pass your ArrayList< Location > to it.

That said, all you need to do in your addLocation(Location l) method in your MainActivity, is add an element to either the Location[] or ArrayList< Location > data structure you passed to your adapter, and then call:

adapter.notifyDataSetChanged();

Note that you'll need to make your adapter a member variable in your MainActivity to allow access outside of your onCreate().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!