有的时候我们需要集成ListActivity,注意点1,这个时候我们的xml中的<ListView>标签中的id属性不能够随便自己命名,而是要固定为android:id="@id/android:list",具体如下:
main3.xml:
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="fill_parent" 4 android:layout_height="fill_parent" 5 android:orientation="vertical" > 6 7 <ListView 8 android:id="@id/android:list" 9 android:layout_width="match_parent" 10 android:layout_height="wrap_content" /> 11 12 </LinearLayout>
我们在activity中想要获取这个ListView的时候,,注意点2,可以直接通过 (ListView) findViewById(android.R.id.list);的方式来获取,这也是固定的。
具体如下:
ListViewDemo.java:
1 package tjuci.edu.dl; 2 3 import android.app.Activity; 4 import android.app.ListActivity; 5 import android.os.Bundle; 6 import android.view.View; 7 import android.widget.ArrayAdapter; 8 import android.widget.ListView; 9 10 public class ListViewDemo extends ListActivity { 11 String[] str = { "wyl", "zhangyalan", "huarong" }; 12 ListView lv; 13 @Override 14 protected void onCreate(Bundle savedInstanceState) { 15 // TODO Auto-generated method stub 16 super.onCreate(savedInstanceState); 17 setContentView(R.layout.main3); 18 ArrayAdapter<String> a = new ArrayAdapter<String>(this, 19 android.R.layout.simple_list_item_1, str); 20 lv = (ListView) findViewById(android.R.id.list); 21 lv.setAdapter(a); 22 } 23 @Override 24 protected void onListItemClick(ListView l, View v, int position, long id) { 25 // TODO Auto-generated method stub 26 super.onListItemClick(l, v, position, id); 27 String selected = l.getItemAtPosition(position).toString(); 28 System.out.println("checkedItem:"+selected+",position:"+position); 29 } 30 31 32 }