Thursday, October 24, 2013

Add Items To ListView Dynamically: Android Tutorial

It can be difficult setting up a ListView in Android using the very basic tools available. It might take awhile getting your head around how the different basic adapters work, so often people just create custom adapters to get things how they want them to be. It's a brute-force method and takes more time than is necessary; all one needs to know is how to use ListActivity and ArrayAdapter to make things shorter and sweeter.

So, let's create an item list which allows us to add text items to it as well as remove them. I'll call the application project "DynamicLV". The main activity will be called "MainActivity" and the layout for it will be called "activity_main." I've set "onClick" in the xml layout file...

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center">
        <Button
            android:id="@+id/addItem"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Add Item"
            android:onClick="onClick"/>
        <Button
            android:id="@+id/deleteItem"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Remove Item"
            android:onClick="onClick"/>
    </LinearLayout>
        <EditText
            android:id="@+id/editText"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="Enter New Item"/>"
        <ListView
              android:id="@android:id/list"
              android:layout_width="match_parent"
              android:layout_height="wrap_content" >
        </ListView>

</LinearLayout>
 Pay attention to the ListView id; this is how we name it when using ListActivity (See MainActivity below)

MainActivity.java
import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;

public class MainActivity extends ListActivity {
                   EditText et;
                  
                   @Override
                   protected void onCreate(Bundle savedInstanceState) {
                       super.onCreate(savedInstanceState);
                       setContentView(R.layout.activity_main);
                       et = (EditText) findViewById(R.id.editText);
                                
                                // use List and not String[]
                       List values = new ArrayList();
                                
                                // simple_list_item_1 is a default row-item layout for ListAdapter     
                       ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                                              android.R.layout.simple_list_item_1, values);
                       setListAdapter(adapter);
                   }
                  
                   public void onClick(View view) {
                           // we're going to add directly to the adapter, so declare it within the method
                           ArrayAdapter<String> adapter = (ArrayAdapter<String>) getListAdapter();
                           String item;
                           //as with the adapter, we're going to add to the List, so declare it
                           List myList = new ArrayList();
                           switch (view.getId()) {
                           case R.id.addItem:
                                     item = et.getText().toString();
                                     myList.add(item);
                                     adapter.add(item);
                                     et.setText("");
                                     break;
                           case R.id.deleteItem:
                                     if (getListAdapter().getCount() > 0) {
                                         // remove the last item added to the list
                                         item = (String) getListAdapter().getItem(getListAdapter().getCount()-1);
                                         myList.remove(item);
                                         adapter.remove(item);
                                     }
                                     break;       
                           }
                           adapter.notifyDataSetChanged();
                   }

                   @Override
                   public boolean onCreateOptionsMenu(Menu menu) {
                                     // Inflate the menu; this adds items to the action bar if it is present.
                                     getMenuInflater().inflate(R.menu.main, menu);
                                     return true;
                   }

}

So, now if we run our application, we have an empty list waiting to be edited...

Now, we add 5 items...

And, finally we remove the last item because, well... it's rubbish, isn't it?...


Using ListActivity and ListAdapter is pretty easy once you get your head around it. As always, thanks for following, and let me know if you have any questions or concerns about this tutorial. Cheers!

NOTE: Don't forget to read up on the relevant API...


No comments:

Post a Comment