ArrayAdapter是一个简单的适配器,他的作用是将一个数组中的内容放入listView中。listView的item必须为textView。
MainActivity.java
1 package com.kale.listview;
2
3 import android.app.Activity;
4 import android.os.Bundle;
5 import android.widget.ArrayAdapter;
6 import android.widget.ListView;
7
8 public class MainActivity extends Activity {
9
10 ListView redLv;
11 @Override
12 protected void onCreate(Bundle savedInstanceState) {
13 super.onCreate(savedInstanceState);
14 setContentView(R.layout.activity_main);
15
16 redLv = (ListView)findViewById(R.id.red_listView_id);
17
18 String []arr01 = {"01","02","03","04","05","06"};
19 //将数组送入arrayAdapter,这里的item对象必须是一个textView。
20 //系统已经默认将数组中的信息放入textView了,所以无需指定额外的id
21 ArrayAdapter<String> adapter01 = new ArrayAdapter<String>(this, R.layout.list_item,arr01);
22 //设置adapter
23 redLv.setAdapter(adapter01);
24 }
25 }
xml
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
2 xmlns:tools="http://schemas.android.com/tools"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent"
5 android:orientation="vertical" >
6
7 <!-- 设置红色分割线的listView -->
8 <ListView
9 android:id="@+id/red_listView_id"
10 android:layout_width="match_parent"
11 android:layout_height="wrap_content"
12 android:divider="#f00"
13 android:dividerHeight="2dp"
14 android:layout_gravity="center"
15 android:headerDividersEnabled="false"/>
16
17
18 </LinearLayout>
listview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/item_textView_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Large Text"
android:gravity="center_horizontal"
android:textAppearance="?android:attr/textAppearanceLarge" />