Use an example to summarize the basic use of ListView.
1. A new project: Listviewdemo.
2. Code in the Main.xml.
<?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:o" rientation= "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 the Strings.xml.
<?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>lyndon B. johnson</item>
<item>richard Nixon</item>
<item>gerald ford</item>
<item>jimmy carter</item>
<item>ronald Reagan</item>
<item>george H. bush</item>
<item>bill clinton</item>
<item>george W. bush</item>
<item>barack obama</item>
</string-array >
</resources>
4. Code in the Listviewdemo.
public class Listviewdemo extends Listactivity {string[] presidents; /** called the activity is a.
* * @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, "H
Ave selected "+ presidents[position], toast.length_short). Show (); }//For button click event public void OnClick (view view) {ListView Lstview = ge
TListView ();
String itemsselected = "Selected items: \ n"; for (int i=0; I<lstview.getcount (); i++) {if (lstview.isitemchecked (i)) {Itemssel
ected + + + lstview.getitematposition (i) + "\ n";
} toast.maketext (this, itemsselected, Toast.length_long). Show (); }
}
5. Press F11 to debug on the simulator. Select objects in the ListView and click the button above to show which objects are selected.
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/OS/extra/