参考《疯狂android讲义》第2.5节P94
1、创建一个或者多个ListView
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context=".MainActivity" > <ListView android:id="@+id/list1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:divider="#f00" android:dividerHeight="2dp" android:headerDividersEnabled="false" /> <ListView android:id="@+id/list2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:divider="#0f0" android:dividerHeight="2dp" android:headerDividersEnabled="true" /> </LinearLayout>
2、创建TextViewResource,为每个元素定义其显示属性
array_item1.xml
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/tv_item1" android:layout_width="match_parent" android:layout_height="match_parent" android:textSize="20sp" android:padding="10dp" android:shadowColor="#0f0" android:shadowDx="4" android:shadowDy="4" android:shadowRadius="2"> </TextView>
array_item2.xml
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/tv_item2" android:layout_width="match_parent" android:layout_height="match_parent" android:textSize="20sp" android:padding="10dp" android:shadowColor="#ff0" android:shadowDx="4" android:shadowDy="4" android:shadowRadius="2"> </TextView>
3、创建Activity,并完成以下三个步骤
package com.ljh.listviewdemo; import android.os.Bundle; import android.app.Activity; import android.widget.ArrayAdapter; import android.widget.ListView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //3、定义每个元素的内容 String[] arr1 = new String[]{"孙悟空","猪八戒","沙僧","唐僧"}; //4、将元素属性及元素内容包装为ArrayAdapter ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, R.layout.array_item1, arr1); //5、为ListView设置Adapter ListView list1 = (ListView) findViewById(R.id.list1); list1.setAdapter(adapter1); //3、定义每个元素的内容 String[] arr2 = new String[]{"Java","C++","Python","PHP"}; //4、将元素属性及元素内容包装为ArrayAdapter ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, R.layout.array_item2, arr2); //5、为ListView设置Adapter ListView list2= (ListView) findViewById(R.id.list2); list2.setAdapter(adapter2); } }