Adapter系列之ArrayAdapter
ArrayAdapter:简单、易用的Adapter,通常用于将List集合的多个值包装成多个列表项。
使用ArrayAdapter创建ListView
activity_main.xml文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/list1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#f00"
android:dividerHeight="2px"
android:headerDividersEnabled="false"/>
<ListView android:id="@+id/list2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#0f0"
android:dividerHeight="2px"
android:headerDividersEnabled="false"/>
</LinearLayout>
item01文件:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24dp"
android:padding="10px"
android:textColor="#00f"/>
item02文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24dp"
android:padding="10px"
android:textColor="#00f"/>
</LinearLayout>
MainActivity文件
package com.example.arrayadaptertest;
import android.app.Activity;
import android.os.Bundle;
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);
ListView list01 = (ListView) findViewById(R.id.list1);
String[] arr1 = {
"我欲乘风来",
"除魔天地间",
"有酒我逍遥"
};
ArrayAdapter<String>adapter01 = new ArrayAdapter<String>(this, R.layout.item01, arr1);
list01.setAdapter(adapter01);
ListView list02 = (ListView) findViewById(R.id.list2);
String[] arr2 = {
"Java",
"C++",
"JavaScript"
};
ArrayAdapter<String>adapter02 = new ArrayAdapter<String>(this,
R.layout.item02, R.id.tv2, arr2);
list02.setAdapter(adapter02);
}
}
截图:
代码太简单,这里就不上传源码了。