ListView和Adapter

别等时光非礼了梦想. 提交于 2020-02-10 02:08:55

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);
这样,就完成了列表信息的显示。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!