It's all about ListViews


     One of the most frequent components used in an android application is a ListView, it's basically a UI component which displays a list of items (simple String items or richer items), with an adapter which can be bound to a ListView and a collection of some sort.

What do we need in order to create a ListView?
Two main options:

1. within the context of an Activity which extends the Activity Class
2. Within the context of an Activity which extends ListActivity (that being said if the whole activity is a 
    list)

We’ll look at the first option
1. Create an Activity, and a matching Xml layout file.
    In the layout file, add a ListView control using <ListView></ListView>, don't forget to give it   
    layout_width,layout_height,id.
    for example:
    <ListView
          android:id="@+id/your_listview_id"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content">
    </ListView>
2. In the Activity, get A reference to the ListView by:
    ListView myListView = (ListView)findViewById(R.id.your_listview_id);
3. Create the actual data that should be populated in the ListView
     for example : 
      String[] names = {"John","Benny","Sharon","Sharona","Simona","Bill"};
      (perhaps a more comfortable way is to create a <string-array> in the resource file under 
      res/values/string.xml).
4. Ok, so far we have an Empty ListView and a collection of data stored in a String Array, we 
    need to be      
    able to bind that data to the listView, for this we will need an adapter:
    ArrayAdapter<String> adapter  =  
                     new ArrayAdapter<String>
                     (this,android.R.layout.simple_list_item_1,names); 

    let's see what are the components:
    1. this - the context
    2. android.R.layout.simple_list_item_1 - this is an id for a single layout of an item in the 
        list (taken by reference directly from the resources of the android SDK, we can see this by 
        the syntax "android.R.layout.simple_list_item_1).
    3. name -  the string array which we've defined.
    
5. finally, we connect the ListView to the adapter by using:
    myListView.setAdapter(adapter);

On the next post, we'll see how we create rich ListView's where each item on the list contains various controls.

Comments

Popular posts from this blog

Spinner VS AutoCompleteTextView

Utilizing Http response cache

ORM for android