Android ListView例子详解
Android ListView例子详解
三种实现方法,由浅入深。这中间要注意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>
- 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,"zhangfei@gmail.com","燕山"),
- new Zhang("张辽",36,"zhangliao@sina.com","雁门"),
- new Zhang("张角",51,"zhangjiao@gmail.com","钜鹿"),
- new Zhang("张三丰",200,"sanfeng@gmail.com","辽东"),
- new Zhang("张牙舞爪",25,"5zhao@gmail.com","冀州"),
- new Zhang("张灯结彩",25,"5zhao@gmail.com","冀州") ,
- new Zhang("张唑啉",25,"5zhao@gmail.com","冀州") ,
- new Zhang("张大民",25,"5zhao@gmail.com","冀州") ,
- new Zhang("张牙舞爪",25,"5zhao@gmail.com","冀州")
- };
- /** 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);
- }
- }
|
评论暂时关闭