ListView 介绍
1. 通过继承Activity实现ListView
1.1 在XML布局文件中实现一个ListView
1 <ListView 2 android:layout_width="wrap_content" 3 android:layout_height="wrap_content" 4 android:id="@+id/listView" 5 android:layout_below="@+id/textView" 6 android:layout_alignParentLeft="true" 7 android:layout_alignParentStart="true" 8 android:layout_marginTop="42dp" />
1.2 在MainActivity中实现代码
1 ListView listView = (ListView) findViewById(R.id.listView); 2 String [] name = new String[]{"A","B","C","D","E","F","Aa","Ba","Ca","Da","Ea","Fa"}; 3 ArrayAdapter<String> arrayAdapter= new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,name); 4 listView.setAdapter(arrayAdapter);
第一步:建立数据源
String [] name = new String[]{"A","B","C","D","E","F","Aa","Ba","Ca","Da","Ea","Fa"};
第二步:建立Adapter并且绑定数据源
ArrayAdapter<String> arrayAdapter= new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,name);
第三步:将Adapter绑定UI
listView.setAdapter(arrayAdapter);
2. 通过继承ListViewActivity实现ListView
2.1 XML文件
不用指定Layout,如果一定要指定话,要将id设为android:id="@android:id/list"
1 <ListView 2 android:layout_width="wrap_content" 3 android:layout_height="wrap_content" 4 android:id="@android:id/list" 5 android:layout_below="@+id/textView" 6 android:layout_alignParentLeft="true" 7 android:layout_alignParentStart="true" 8 android:layout_marginTop="42dp" />
2.2 继承ListActivity
1 public class MainActivity extends ListActivity { 2 3 @Override 4 protected void onCreate(Bundle savedInstanceState) { 5 super.onCreate(savedInstanceState); 6 String [] name = new String[]{"A","B","C","D","E","F","Aa","Ba","Ca","Da","Ea","Fa"}; 7 ArrayAdapter<String> arrayAdapter= new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,name); 8 setListAdapter(arrayAdapter); 9 }
如果设定XML文件,且指定id为android:id="@android:id/list"
可以用 ListView listView = getListView();来得到这个id为list的listView,然后就可以对这个listView进行操作了。