An example is provided to summarize the basic usage of ListView.
1. Create a project: ListViewDemo.
2. Code in main. xml.
[Html]
<? Xml version = "1.0" encoding = "UTF-8"?>
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
Android: orientation = "vertical">
<Button android: id = "@ + id/btn"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: text = "Show selected items"
Android: onClick = "onClick"/>
<ListView
Android: id = "@ + id/android: list"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"/>
</LinearLayout>
3. Code in Strings. xml.
[Html]
<? Xml version = "1.0" encoding = "UTF-8"?>
<Resources>
<String name = "hello"> Hello World, BasicViews5Activity! </String>
<String name = "app_name"> BasicViews5 </string>
<String-array name = "presidents_array">
<Item> Dwight D. Eisenhower </item>
<Item> John F. Kennedy </item>
<Item> lyw. B. Johnson </item>
<Item> Richard Nixon </item>
<Item> Gerald Ford </item>
<Item> Jimmy Carter </item>
<Item> Ronald Reagan </item>
<Item> George H. W. Bush </item>
<Item> Bill Clinton </item>
<Item> George W. Bush </item>
<Item> Barack Obama </item>
</String-array>
</Resources>
4. Code in ListViewDemo.
[Java]
Public class ListViewDemo extends ListActivity {
String [] presidents;
/** Called when the activity is first created .*/
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
ListView lstView = getListView ();
// LstView. setChoiceMode (ListView. CHOICE_MODE_NONE );
// LstView. setChoiceMode (ListView. CHOICE_MODE_SINGLE );
LstView. setChoiceMode (ListView. CHOICE_MODE_MULTIPLE );
LstView. setTextFilterEnabled (true );
Presidents =
GetResources (). getStringArray (R. array. presidents_array );
SetListAdapter (new ArrayAdapter <String> (this,
Android. R. layout. simple_list_item_checked, presidents ));
}
Public void onListItemClick (
ListView parent, View v, int position, long id)
{
Toast. makeText (this,
"You have selected" + presidents [position],
Toast. LENGTH_SHORT). show ();
}
// For button click event
Public void onClick (View view ){
ListView lstView = getListView ();
String itemsSelected = "Selected items: \ n ";
For (int I = 0; I <lstView. getCount (); I ++ ){
If (lstView. isItemChecked (I )){
ItemsSelected + = lstView. getItemAtPosition (I) + "\ n ";
}
}
Toast. makeText (this, itemsSelected, Toast. LENGTH_LONG). show ();
}
}
5. Press F11 to debug the simulator. Select some objects in the ListView and click the Button above to display which objects have been selected.
The ListView function is far more than that, for example, setting the ListView animation, auto-defining the display and Sliding Modes of the ListView, and so on. Please discover it yourself at work and study ~~~