0

I have created new ListView in my app, I have my ListView, and in an ActionBar there is a button "add new". The button's function is to make a new item in the ListView.

My question is: How can I make a new String in my ListView when the button is pushed?

Neil Townsend
  • 6,024
  • 5
  • 35
  • 52
AndroidFreak
  • 866
  • 1
  • 10
  • 31

4 Answers4

3

This is example if you need only simple String rows.

  ListView lv = (ListView) findViewById(R.id.mylist);
        String[] values = new String[] { "Android", "Linux", "OSX", 
                "WebOS", "Windows7", "Ubuntu", "OS/2"
        };
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.rowlayout,   R.id.restaurantname, values);
    lv.setAdapter(adapter);
adapter.add("another row");
    adapter.notifyDataSetChanged()
sh0m1
  • 536
  • 4
  • 7
1

ListView are widgets that display multiple Views that are managed by an Adapter. To be specific, a ListAdapter.

You need to add an adapter to your listview widget, and use that adapter to add new items to the listview.

For example; you could add an ArrayAdapter and call the add method when a user clicks the ActionBar item.

Here is a tutorial on using ArrayAdapters.

In the most basic form. You can tell ArrayAdapter to use an existing Layout and TextView. So adding a string should be straightforward.

Reactgular
  • 52,335
  • 19
  • 158
  • 208
1

Basically tou have to do some like this:

your_btn.setOnClickListener(new View.OnClickListener
{
   public void onClick(View v)
   {
     your_custom_adapter.Add('Foo');
     your_custom_adapter.notifyDataSetChanged();
   }
});

The implementation for method Add in your adapter is obvious,it just adds a new String to your data structure(i.e: an ArrayList).

Good Luck

Daniel Conde Marin
  • 7,588
  • 4
  • 35
  • 44
0

If you mean: adding a new item to list with button click, It is certainly bounded to what model you used is your list adapter. A database, a file or just a runtime List<>(); Your list is connected with an adapter; the method "getViewAt" returns every row in your listview.

If you used a database model for listview, you run an insert script in your activity for button click, database refreshes its data, your listview adapter retrieves data from DB and it's done.

Or if you're just using a simple List<> in your adapter; you will do list.add in your click & adapter does the rest.

Sample at vogella, using Map as data modeling: Listview sample

sophocan
  • 31
  • 5