Android ListView 的简单用法

参考 API 和《第一行代码》

  1. ListView is a view group that displays a list of scrollable items. The list items are automatically inserted to the list using an Adapter that pulls content from a source such as an array or database query and converts each item result into a view that’s placed into the list.
  2. When the content for your layout is dynamic or not pre-determined, you can use a layout that subclasses AdapterView to populate the layout with views at runtime. A subclass of the AdapterView class uses an Adapter to bind data to its layout. The Adapter behaves as a middleman between the data source and the AdapterView layout—the Adapter retrieves the data (from a source such as an array or a database query) and converts each entry into a view that can be added into the AdapterView layout.

ListView 用来显示一个可以垂直滚动的列表,其中列表的每一项由其相关联的适配器提供,适配器起到一个中间人的作用,即连接列表数据和ListView布局
-
使用默认 ListView, 先定义一个数组(ArrayList)保存要在ListView里显示的数据,然后新建一个适配器,构造函数传入系统默认的子项目布局( android.R.layout.simple_list_item_1 )–(显示一个 TextView )和数据存在的数组,再直接调用 ListView 的 setAdapter() 方法,传入新建好的适配器,即可显示数据.

使用自定义的 ListView, 可以在子项目中不只显示一个 TextView, 而是可以显示其他自己定义的布局,所以要

  1. 先新建一个子项目布局,里面可以添加 TextView, Button, ImageView 等控件;
  2. 后新建一个类 Item 与子项目布局里的控件对应,用作 List<\T> 的范型和要继承的 ArrayAdapter<\T> 的范型,也是要显示的数据类型;
  3. 自定义 Adapter 类扩展自 ArrayAdapter<\T>, 重写 getView() 方法,先 getItem(position) 获取当前 Item 实例,然后 LayoutInflater.from(getContext()).inflate(resourceId,parent,false) 获取子项目布局 View 实例,再通过 View.findViewById() 获取子项目布局里的控件实例,最后调用 setText() 等控件方法完成控件的操作,返回 View.
  4. 然后和使用默认 ListView 一样,新建一个自定义的适配器,传入自定义的子项目布局和要显示的数据,再直接调用 ListView 的 setAdapter() 方法,传入新建好的适配器,即可显示数据.
  5. 要增加新的数据,只需要调用 Adapter.add(Item) 即可.

例 :

public class Item {
   
    private String text;
    private int button;
    
    public Item(String text,int button){
   
        this.text=text;
        this.button=button;
    }
    public String getText(){
   
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值