Monday, February 24, 2014

Android: ListViews

Android : ListViews

The Steps that need to be followed in order to create a ListView are:
1. Create an array of data source
2. Create a ListAdapter and specify it how to display the array elements (here an individual view - TextView is created for each array item)
3. Define the action that needs to be taken when the user interacts with the ListView (by adding appropriate listener to it)

ListView is a view group which has a set of scrollable elements or items in it. To create a ListView with three items, these are the steps that need to be followed:
1. Open the layout file (.xml)
2. Drag and drop ListView item from under the Composite widget. A ListView gets created with the id listView1
3. Open the Java file and do the following steps:
     //Get the resource of the listview from the R file      
final ListView listview = (ListView) findViewById(R.id.listView1);

    //Create an array of Strings (the elements that you want the listview to display
String[] values = new String[] { "Pride & Prejudice", "David Copperfield", "To Sir, With Love" };

    //Create an ArrayList from the string array
final ArrayList<String> list = new ArrayList<String>();
    for (int i = 0; i < values.length; ++i) {
      list.add(values[i]);
    }

    //List items are added to the list with the help of an adapter. Create and ArrayAdapter
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.activity_list_item, android.R.id.text1, list);

   //set the adapter with the listview
    listview.setAdapter(adapter);
  

The Constructor for ArrayAdapter that is used here is:

public ArrayAdapter (Context context, int resource, int textViewResourceId, List<T>objects)


context : The current context (used this here)
resource : The resource ID for a layout file containing a layout to use when instantiating views (used the activity_list_item here - it gets populated automatically)
textViewResourceId : The id for the TextView within the layout resource to be populated (used text1 -it gets populated automatically)
objects : the array ArrayList that has been created with the items

This will make your ListView appear with the list items in it. 

No comments:

Post a Comment