Display a long list of items using the ListView
1. Create a new Android project called "BasicView5";
2, modify the Basicview5.java file, the revised program is as follows:
Package Com.example.basicview5;import Android.os.bundle;import Android.app.activity;import Android.app.listactivity;import Android.view.menu;import Android.view.view;import Android.widget.ArrayAdapter; Import Android.widget.listview;import Android.widget.toast;public class Mainactivity extends Listactivity {String[] Presidents = {"Dwight D. Eisenhower", "John F. Kennedy", "Lyndon B. Johnson", "Richard Nixon", "Gerald Ford", "Jimmy Carter "," Ronald Reagan "," George H. W. Bush "," Bill Clinton "," George W. Bush "," Barack Obama "}; @Overrideprotected void Oncreat E (Bundle savedinstancestate) {super.oncreate (savedinstancestate);//---No need to call this---////setcontentview ( R.layout.activity_main) Setlistadapter (New arrayadapter<string> (this,android. R.layout.simple_expandable_list_item_1, Presidents));} public void Onlistitemclick (ListView parent, View v, int position, long id) {Toast.maketext (this, "You have selected" + P Residents[position],toast.length_short). Show ();} @Overridepublic BooLean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is Present.getmenuinflat ER (). Inflate (R.menu.main, menu); return true;}}
3. Running results: For example, after clicking on "Richard Nixon":
Detailed
(1) The BasicView5 class extends the Listactivity class, and the Listactivity class extends the activity class and displays a list of items by binding to a data source;
(2) without modifying main.xml to include the Listview:listactivity class itself already contains a ListView, so in the OnCreate () method, you do not need to call Setcontentview () method to load the user interface from the Main.xml file;
(3) in the OnCreate () method, use the Setlistadapter () method to programmatically populate the active entire screen with a ListView. The Arrayadapter object manages an array of strings that will be displayed by the ListView;
(4) When you click a list item in a ListView, The Onlistitemclick () method is triggered;
Next to implement a custom general view of the ListView ~