One of the simple views is a List View. In this post, I will explore a very simple list view using all the defaults provided by Android SDK and introduce you to a customized list view in the next blog article.
A List View, by name means being able to display a list of items in an order one below the other. For creating such a view, the first thing we have to do is extend the ‘ListActivity’ (android.app.ListActivity) instead of the normal Activity class.
public class MyListView extends ListActivity {The ListActivity class provides a way of binding a source of data (an array or a cursor) to a ListViewobject through a ListAdapter.
In android, we all know that views are defined declaratively in XML files. It is the same here too. So, if we were to create our own custom ListView, we would have a declaration of this type:
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000fff"
android:layout_weight="2"
android:drawSelectorOnTop="false">
However, if no ListView is declared, the ListActivity picks up a default ListView which fills the screen. So, in our example we will not declare any list view.
There is one more thing we need to define and that is how each row in the list should show up. This again, there are some defaults available which have names such as simple_list_item_1, simple_list_item_2, and two_line_list_item. So, in our example, I do not declare the layout for the rows but I will be using one of the defaults provided. So, in effect, I have not declared any layout – I am using the default screen layout and row layout.
Now, that we have the layouts out of our way, what else do we need for a List View. Of course, the list of data that needs to be displayed. Just to keep it simple, I will use an array of data for the same. So, here it is:
static final String[] PENS = new String[]{setListAdapter(new ArrayAdapter
"MONT Blanc",
"Gucci",
"Parker",
"Sailor",
"Porsche Design",
"Rotring",
"Sheaffer",
"Waterman"
};
With this we are done in creating the ListView.
I have added a small piece of code to show we can handle events on selecting an item in the list, by overriding the protected method shown below:
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Object o = this.getListAdapter().getItem(position);
String pen = o.toString();
Toast.makeText(this, "You have chosen the pen: " + " " + pen, Toast.LENGTH_LONG).show();
}
This toasts a message with the item selected.
The complete code is downloadable here.
No comments:
Post a Comment