ArrayAdapter
- 定义simple_item.xml,仅包含一个TextView
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tv_item"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="示例文本"
android:textSize="40sp" >
</TextView>
- 创建ArrayAdapter并应用到ListView
public class MainActivity extends Activity {
private ListView lv_data;
private ListAdapter adapter;
private String[] names = new String[] { "1", "2", "3", "4", "5" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv_data = (ListView) findViewById(R.id.lv_data);
adapter = new ArrayAdapter<String>(this, R.layout.simple_item, R.id.tv_item, names);
lv_data.setAdapter(adapter);
}
}
SimpleAdapter
- 定义complex_item.xml
<?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/tvc_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/tvc_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:text="Number"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
- 创建SimpleAdapter并应用到ListView
public class MainActivity extends Activity {
private List<String[]> keys;
private ListView lv_data;
private ListAdapter adapter;
private List<Map<String, String>> data = new ArrayList<Map<String, String>>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (int i = 0; i < keys.size(); i++) {
Map<String, String> map = new HashMap<String, String>();
map.put("name", keys.get(i)[0]);
map.put("number", keys.get(i)[1]);
data.add(map);
}
adapter = new SimpleAdapter(this, data, R.layout.complex_item, new String[] { "name", "number" },
new int[] { R.id.tvc_name, R.id.tvc_number });
lv_data = (ListView) findViewById(R.id.lv_data);
lv_data.setAdapter(adapter);
}
}