ArrayAdapter是一个简单的适配器,他的作用是将一个数组中的内容放入listView中。listView的item必须为textView。
MainActivity.java
package com.kale.listview; import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView; public class MainActivity extends Activity { ListView redLv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); redLv = (ListView)findViewById(R.id.red_listView_id); String []arr01 = {"01","02","03","04","05","06"};
//将数组送入arrayAdapter,这里的item对象必须是一个textView。
//系统已经默认将数组中的信息放入textView了,所以无需指定额外的id
ArrayAdapter<String> adapter01 = new ArrayAdapter<String>(this, R.layout.list_item,arr01);
//设置adapter
redLv.setAdapter(adapter01);
}
}
xml
<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:orientation="vertical" > <!-- 设置红色分割线的listView -->
<ListView
android:id="@+id/red_listView_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#f00"
android:dividerHeight="2dp"
android:layout_gravity="center"
android:headerDividersEnabled="false"/> </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" />