三種實現方法,由淺入深。這中間要注意Adapter的用法,其實你要是看過Android的文檔,你會發現有很多Adapter,
如果你還不太清楚適配器模式,可以先補補這方面的知識。在實際工作中,設計模式是個很好的幫手。
兩個layout文件:
main.xml
[html]
- <?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:orientation="vertical" >
-
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello" />
-
- <ListView
- android:id="@+id/listview"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- ></ListView>
-
- </LinearLayout>
listview.xml
[html]
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/linerlayout1"
- android:orientation="vertical"
- android:layout_height="fill_parent"
- android:layout_width="fill_parent"
- >
- <TextView
- android:id="@+id/person_name"
- android:textSize="23sp"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- />
- <TextView
- android:id="@+id/person_age"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- />
- <TextView
- android:id="@+id/person_email"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- />
- <TextView
- android:id="@+id/person_address"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- />
- </LinearLayout>
Activity:LincListViewActivity.java
[java]
- package com.linc.listview;
-
- import android.app.Activity;
- import android.os.Bundle;
- import android.widget.ArrayAdapter;
- import android.widget.ListView;
-
- public class LincListViewActivity extends Activity {
- private final static String[] data = {"張飛","張遼","張角","張三豐","張牙舞爪","張燈結彩","張唑啉","張大民"};
-
- //創建數據源.
- Zhang[] data2 = new Zhang[]{
- new Zhang("張飛",38,"[email protected]","燕山"),
- new Zhang("張遼",36,"[email protected]","雁門"),
- new Zhang("張角",51,"[email protected]","钜鹿"),
- new Zhang("張三豐",200,"[email protected]","遼東"),
- new Zhang("張牙舞爪",25,"[email protected]","冀州"),
- new Zhang("張燈結彩",25,"[email protected]","冀州") ,
- new Zhang("張唑啉",25,"[email protected]","冀州") ,
- new Zhang("張大民",25,"[email protected]","冀州") ,
- new Zhang("張牙舞爪",25,"[email protected]","冀州")
- };
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- ListView listview = (ListView)findViewById(R.id.listview);
- /*
- * 第一種:普通字符串
- */
- ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
- android.R.layout.simple_list_item_1,data);
-
- /*
- * 第二種:文藝類對象
- */
- ArrayAdapter<Zhang> adapter2 = new ArrayAdapter<Zhang>(this,
- android.R.layout.simple_list_item_1,data2);
-
- /*
- * 第三種:自定義適配器
- */
- ListAdapter adapter3 = new ListAdapter(this, R.layout.listview,data2) ;
-
- listview.setAdapter(adapter3);
- }
- }