Android开发高级组件--ListView(列表显示组件)

1、与ScrollView类似的还有一种列表组件ListView,它可以将多个组件加入到ListView中以达到组件的滚动显示效果。

2、ListView层次关系如下所示:
   java.lang.Object
      android.view.View
         android.view.ViewGroup
            android.widget.AdapterView<T extends android.widget.Adapter>
               android.widget.AbsListView
                  android.widget.ListView

3、ListView是一个经常用到的组件,它里面的每一个子项Item可以是一个字符串,也可以是一个组合组件。要实现ListView组件,有如下步骤:
   1)准备ListView要显示的数据。
   2)构建适配器,就是Item数组,动态数组有多少元素就生成多少个Item。适配器常见的3种类型:ArrayAdapter、SimpleAdapter和SimpleCursorAdapter。ArrayAdapter最简单,只能显示一行文字,SimpleAdapter有最好的扩充性,可以自定义各种效果。SimpleCursorAdapter是SimpleAdapter对数据库的简单结合,可以方便地把数据库记录以列表的形式展示出来。SimpleAdapter继承自AdapterView,可以通过一些方法给ListView添加监听器,当用户单击某一个列表项执行相应的操作。
   3)把适配器添加到ListView并显示出来。

4、新建布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/LinearLayout">

    <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

5、新建ListViewActivity.java
package xiao.fuyan.testapp;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

/**
* Created by xiao on 2017/1/1.
*/
public class ListViewActivity extends Activity {

    private String listData[] = {"信息学院", "机械学院", "计算机学院", "新闻学院", "化工学院",
            "美术学院", "计算机学院", "新闻学院", "化工学院", "美术学院", "体育学院", "音乐学院",
            "经济管理学院", "南湖学院", "物理与电子学院", "机电学院", "法律学院", "外语学院",
            "科技处", "图书馆", "教务处", "网络中心", "学工处", "财务处","信息学院", "机械学院", "计算机学院", "新闻学院", "化工学院",
            "美术学院", "计算机学院", "新闻学院", "化工学院", "美术学院", "体育学院", "音乐学院",
            "经济管理学院", "南湖学院", "物理与电子学院", "机电学院", "法律学院", "外语学院",
            "科技处", "图书馆", "教务处", "网络中心", "学工处", "财务处"};
    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview_xml);

        listView = (ListView) findViewById(R.id.listView);
        listView.setAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_expandable_list_item_1,listData));
    }
}


猜你喜欢

转载自xiaofuyan.iteye.com/blog/2348310