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.
- Using ListActivity .
- 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 :
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
Here i am just setting the layout as a linear layout and giving the properties.
And the Activity File looks like this :
- public class ListExampleActivity extends ListActivity implements
- OnItemClickListener {
- /** Called when the activity is first created. */
- ArrayAdapter aa;
- ListView lv;
- String[] months = { "January", "February", "March", "April", "May", "June", "July" ,"August" ,"September", "October", "November" ,"December"};
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- aa = new ArrayAdapter(this,
- android.R.layout.simple_list_item_1, months);
- setListAdapter(aa);
- lv = getListView();
- lv.setOnItemClickListener(this);
- }
- public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
- // TODO Auto-generated method stub
- Toast.makeText(this,
- "Item is clicked " + ((TextView) arg1).getText() + " " + arg2,
- 600).show();
- }
- }
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
Comments
Post a Comment