Wednesday, 18 July 2012

Android List View sample

List View  :  As the name suggests it displays items in a list.  The user gets a list of items (a scrollable one when the number of items are not sufficient in the screen )  and when clicked on any item in the list view displays details about the clicked item.
By default the list items are textViews.
If you observe a list view can be seen in Contacts list , messages , songs list etc in a mobile .
A listView can be implemented in Android in two ways.
  1. Using  ListActivity .
  2. Using  ListView in XML file .
Using listActivity

In this we dont write anything in the xml file except the layout. 
My sample xml file looks like this :

Here i am just setting the layout as a linear layout and giving the properties.

And the Activity File looks like this :
  1.  public class ListExampleActivity extends ListActivity implements
  2. OnItemClickListener {
  3. /** Called when the activity is first created. */

  4. ArrayAdapter aa;
  5. ListView lv;
  6. String[] months = { "January", "February", "March", "April", "May", "June", "July" ,"August"       ,"September", "October",  "November" ,"December"};

  7. @Override
  8. public void onCreate(Bundle savedInstanceState) {
  9. super.onCreate(savedInstanceState);

  10. aa = new ArrayAdapter(this,
  11. android.R.layout.simple_list_item_1, months);
  12. setListAdapter(aa);

  13. lv = getListView();
  14. lv.setOnItemClickListener(this);

  15. }

  16. public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
  17. // TODO Auto-generated method stub
  18. Toast.makeText(this,
  19. "Item is clicked " + ((TextView) arg1).getText() + "  " + arg2,
  20. 600).show();
  21. }
  22. }

Adapters are used in order to bind data with views.
In the similar way i am binding the data (the string array ) with the view (list view) using adapters.
Check the line 1 : we are using a ListActivity. 
       line 13 :  creates a arrayadapter with the data binded to it as the last parameter(months)
       line 17  : getting the default list view .
    line 18  : Setting the click event for the list item. (This will invoke the onItemClick())
    line 23  :   Displays the item that is clicked.

There is no need to change the manifest file for this task.

You can also use XML file to get a list layout.

The output will look something like this

No comments:

Post a Comment