ListView和Adapter
ListView控件和Adapter
这次的作业是利用ListView和自定义Adapter完成列表信息的显示,首先
用ListView在XML中定义如下:
<ListView
android:id="@+id/Listview"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</ListView>
另一个listview_xml的布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/name" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/age" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/com" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/adress" />
</LinearLayout>
</LinearLayout>
接下来是Java代码:用SimpleAdapter适配器显示列表
1)准备数据源:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Map<String, Object>> listems = new ArrayList<>();
for (int q = 0; q < name.length; q++) {
Map<String, Object> listem = new HashMap<>();
listem.put("name", "姓名:" + name[q]);
listem.put("age", "年龄:" + age[q]);
listem.put("com", "邮箱:" + com[q]);
listems.add(listem);
}
2)创建适配器:
SimpleAdapter sim= new SimpleAdapter(this, listems,
R.layout.support_simple_spinner_dropdown_item, new String[]{"name", "age", "adress"},
new int[]{R.id.name, R.id.age, R.id.adress});
listView1 = (ListView) findViewById(R.id.Listview);
3)为ListView绑定适配器:
listView1.setAdapter(sim);
这样,就完成了列表信息的显示。