1. 通过继承Activity实现ListView
1.1 在XML布局文件中实现一个ListView
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listView"
android:layout_below="@+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="42dp" />
1.2 在MainActivity中实现代码
ListView listView = (ListView) findViewById(R.id.listView);
String [] name = new String[]{"A","B","C","D","E","F","Aa","Ba","Ca","Da","Ea","Fa"};
ArrayAdapter<String> arrayAdapter= new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,name);
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"
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@android:id/list"
android:layout_below="@+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="42dp" />
2.2 继承ListActivity
public class MainActivity extends ListActivity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String [] name = new String[]{"A","B","C","D","E","F","Aa","Ba","Ca","Da","Ea","Fa"};
ArrayAdapter<String> arrayAdapter= new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,name);
setListAdapter(arrayAdapter);
}
如果设定XML文件,且指定id为android:id="@android:id/list"
可以用 ListView listView = getListView();来得到这个id为list的listView,然后就可以对这个listView进行操作了。