高级控件ListView

本文详细探讨了ListView的高级用法,包括自定义BaseAdapter以实现完全定制,利用LayoutInflater解析布局,以及ListView的性能优化策略。重点讲解了如何通过ConvertView重用组件,使用ViewHolder减少查找控件的开销,实现分页查询优化,如PullToRefresh和AsyncTask。同时,文章提出了事件监听优化的方法,避免过多的OnClickListener对象。最后,提到了在实际开发中图片的异步下载优化策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. BaseAdapter:是所有适配器类的父类,可以对列表项进行最大限度的定制
    1.1 自定义适配器中的方法
    getCount
    getView
    getItem
    getItemId
    1.2 LayoutInflater(布局解析器)
    –LayoutInflater有三种获得方式,资料中有详细介绍
    用来把layout布局文件解析成一个View对象,不可以new,需要使用系统服务获得
    inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

案例一:ListView的使用及优化
2. ListView优化
2.1 使用ConvertView重用组件
即拖动时被遮住、看不见的控件,重用它,而非每次创建一个新的对象

2.2 使用内部类ViewHolder+ConvertView.setTag()保存控件,而不用每次查找
ViewHolder(视图的持有者)

2.3 使用分页查询(PullToRefresh)
2.3.2 使用AsyncTask(异步任务)加载数据,最少要重写以下这两个方法
doInBackground
后台执行
onPostExecute
在doInBackground方法执行结束之后在运行,并且运行在UI线程当中 可以对UI空间进行设置
关键代码:
myListViewAdapter.notifyDataSetChanged();// 通知适配器数据已改变
ptrlv_main_1.onRefreshComplete();// 通知控件数据已经加载完毕

2.4 事件监听的优化
假设Item中有三个按钮,要为三个按钮定义事件,如果是下面这样
btn1.setOnclickListener(new View.onClickListener(){
public void onClick(View view){
//…
}
});
btn2.setOnclickListener(new View.onClickListener(){
public void onClick(View view){
//…
}
});
btn3.setOnclickListener(new View.onClickListener(){
public void onClick(View view){
//…
}
});
如果每屏显示10个Item,那一共创建了30个listener对象在内存中。
如果,你是在Adapter创建时,只创建一个Listener,并将其定义成全局属性,
然后通过按钮的ID来进行判断是哪个事件应该触发,
class MyAdapter extends BaseAdapter{
View.onClickListener myListener = new View.onClickListener(){
public void onClick(View view){
if(view.getId() == R.id.btn1){
//…
}else if(view.getId() == R.id.btn2){
//…
}else if(view.getId() == R.id.btn3){
//…
}
}
});
}

//注册监听器
btn1.setOnclickListener(myListener);
btn2.setOnclickListener(myListener);
btn3.setOnclickListener(myListener);

2.5 另外,真实开发中,图片肯定是通过网络下载,也需要通过线程异步下载进行优化等等。

导入4个类:
实体类:

package com.example.android14_advancewidget06_d01;  
public class Book {
    private Integer id;
    private String title;
    private String author;

    private Float price;
    private String publish;
    private String remark;

    private int image;

    public Book() {
        super();
    }

    public int getImage() {
        return image;
    }

    public void setImage(int image) {
        this.image = image;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Float getPrice() {
        return price;
    }

    public void setPrice(Float price) {
        this.price = price;
    }

    public String getPublish() {
        return publish;
    }

    public void setPublish(String publish) {
        this.publish = publish;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

}

BookDao:
package com.example.android14_advancewidget06_d01;

import java.util.ArrayList;
import java.util.List;

public class BookDao {

private int[] bookImages = new int[] { R.drawable.book1, R.drawable.book2,
        R.drawable.book3, R.drawable.book4, R.drawable.book5,
        R.drawable.book6, R.drawable.book7, R.drawable.book8,
        R.drawable.book9, R.drawable.book10 };

public List<Book> list() {
    List<Book> list = new ArrayList<Book>();
    for (int i = 1; i <= 1000; i++) {
        Book b = new Book();
        b.setId(i);
        b.setTitle("t" + i);
        b.setAuthor("a" + i);
        b.setPrice(0.0f + i);
        b.setPublish("p" + i);
        b.setRemark("r" + i);
        // 真实开发图片应该是从网络获取,而非本地获得
        b.setImage(bookImages[i % bookImages.length]);

        list.add(b);
    }

    return list;
}

}

创建一个项资源 listview_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="wrap_content"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/iv_listviewitem_image"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3"
        android:padding="10dp"
        android:scaleType="fitXY"
        android:src="@drawable/book1" />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="6"
        android:orientation="vertical"
        android:padding="10dp" >

        <TextView
            android:id="@+id/tv_listviewitme_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="狂人摄影日记"
            android:textColor="@color/red"
            android:textSize="20sp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:text="书本作者:"
                android:textColor="@color/black" />

            <TextView
                android:id="@+id/tv_listviewitme_author"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="3"
                android:text="阿刘" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:text="书本价格:"
                android:textColor="@color/black" />

            <TextView
                android:id="@+id/tv_listviewitme_price"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="3"
                android:text="$123"
                android:textColor="@color/black" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:text="    出版社:"
                android:textColor="@color/black" />

            <TextView
                android:id="@+id/tv_listviewitme_publish"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="3"
                android:text="电子出版社"
                android:textColor="@color/black" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:text="书本简介:"
                android:textColor="@color/black" />

            <TextView
                android:id="@+id/tv_listviewitme_remark"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="3"
                android:ellipsize="end"
                android:maxLines="2"
                android:text="很冷的一个冬天很冷的一个冬天很冷的一个冬天很冷的一个冬天很冷的一个冬天很冷的一个冬天很冷的一个冬天很冷的一个冬天很冷的一个冬天很冷的一个冬天"
                android:textColor="@color/black" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="20dp"
            android:orientation="horizontal" >

            <ImageButton
                android:id="@+id/bt_listviewitme_btn1"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:src="@drawable/btn_shopping" />

            <ImageButton
                android:id="@+id/bt_listviewitme_btn2"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:src="@drawable/btn_accounts" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>

colors.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#008577</color>
    <color name="colorPrimaryDark">#00574B</color>
    <color name="colorAccent">#D81B60</color>
    <color name="white">#ffffff</color><!--白色 -->
    <color name="ivory">#fffff0</color><!--象牙色 -->
    <color name="lightyellow">#ffffe0</color><!--亮黄色 -->
    <color name="yellow">#ffff00</color><!--黄色 -->
    <color name="snow">#fffafa</color><!--雪白色 -->
    <color name="floralwhite">#fffaf0</color><!--花白色 -->
    <color name="lemonchiffon">#fffacd</color><!--柠檬绸色 -->
    <color name="cornsilk">#fff8dc</color><!--米绸色 -->
    <color name="seaShell">#fff5ee</color><!--海贝色 -->
    <color name="lavenderblush">#fff0f5</color><!--淡紫红 -->
    <color name="papayawhip">#ffefd5</color><!--番木色 -->
    <color name="blanchedalmond">#ffebcd</color><!--白杏色 -->
    <color name="mistyrose">#ffe4e1</color><!--浅玫瑰色 -->
    <color name="bisque">#ffe4c4</color><!--桔黄色 -->
    <color name="moccasin">#ffe4b5</color><!--鹿皮色 -->
    <color name="navajowhite">#ffdead</color><!--纳瓦白 -->
    <color name="peachpuff">#ffdab9</color><!--桃色 -->
    <color name="gold">#ffd700</color><!--金色 -->
    <color name="pink">#ffc0cb</color><!--粉红色 -->
    <color name="lightpink">#ffb6c1</color><!--亮粉红色 -->
    <color name="orange">#ffa500</color><!--橙色 -->
    <color name="lightsalmon">#ffa07a</color><!--亮肉色 -->
    <color name="darkorange">#ff8c00</color><!--暗桔黄色 -->
    <color name="coral">#ff7f50</color><!--珊瑚色 -->
    <color name="hotpink">#ff69b4</color><!--热粉红色 -->
    <color name="tomato">#ff6347</color><!--西红柿色 -->
    <color name="orangered">#ff4500</color><!--红橙色 -->
    <color name="deeppink">#ff1493</color><!--深粉红色 -->
    <color name="fuchsia">#ff00ff</color><!--紫红色 -->
    <color name="magenta">#ff00ff</color><!--红紫色 -->
    <color name="red">#ff0000</color><!--红色 -->
    <color name="oldlace">#fdf5e6</color><!--老花色 -->
    <color name="lightgoldenrodyellow">#fafad2</color><!--亮金黄色 -->
    <color name="linen">#faf0e6</color><!--亚麻色 -->
    <color name="antiquewhite">#faebd7</color><!--古董白 -->
    <color name="salmon">#fa8072</color><!--鲜肉色 -->
    <color name="ghostwhite">#f8f8ff</color><!--幽灵白 -->
    <color name="mintcream">#f5fffa</color><!--薄荷色 -->
    <color name="whitesmoke">#f5f5f5</color><!--烟白色 -->
    <color name="beige">#f5f5dc</color><!--米色 -->
    <color name="wheat">#f5deb3</color><!--浅黄色 -->
    <color name="sandybrown">#f4a460</color><!--沙褐色 -->
    <color name="azure">#f0ffff</color><!--天蓝色 -->
    <color name="honeydew">#f0fff0</color><!--蜜色 -->
    <color name="aliceblue">#f0f8ff</color><!--艾利斯兰 -->
    <color name="khaki">#f0e68c</color><!--黄褐色 -->
    <color name="lightcoral">#f08080</color><!--亮珊瑚色 -->
    <color name="palegoldenrod">#eee8aa</color><!--苍麒麟色 -->
    <color name="violet">#ee82ee</color><!--紫罗兰色 -->
    <color name="darksalmon">#e9967a</color><!--暗肉色 -->
    <color name="lavender">#e6e6fa</color><!--淡紫色 -->
    <color name="lightcyan">#e0ffff</color><!--亮青色 -->
    <color name="burlywood">#deb887</color><!--实木色 -->
    <color name="plum">#dda0dd</color><!--洋李色 -->
    <color name="gainsboro">#dcdcdc</color><!--淡灰色 -->
    <color name="crimson">#dc143c</color><!--暗深红色 -->
    <color name="palevioletred">#db7093</color><!--苍紫罗兰色 -->
    <color name="goldenrod">#daa520</color><!--金麒麟色 -->
    <color name="orchid">#da70d6</color><!--淡紫色 -->
    <color name="thistle">#d8bfd8</color><!--蓟色 -->
    <color name="lightgray">#d3d3d3</color><!--亮灰色 -->
    <color name="lightgrey">#d3d3d3</color><!--亮灰色 -->
    <color name="tan">#d2b48c</color><!--茶色 -->
    <color name="chocolate">#d2691e</color><!--巧可力色 -->
    <color name="peru">#cd853f</color><!--秘鲁色 -->
    <color name="indianred">#cd5c5c</color><!--印第安红 -->
    <color name="mediumvioletred">#c71585</color><!--中紫罗兰色 -->
    <color name="silver">#c0c0c0</color><!--银色 -->
    <color name="darkkhaki">#bdb76b</color><!--暗黄褐色 -->
    <color name="rosybrown">#bc8f8f</color><!--褐玫瑰红 -->
    <color name="mediumorchid">#ba55d3</color><!--中粉紫色 -->
    <color name="darkgoldenrod">#b8860b</color><!--暗金黄色 -->
    <color name="firebrick">#b22222</color><!--火砖色 -->
    <color name="powderblue">#b0e0e6</color><!--粉蓝色 -->
    <color name="lightsteelblue">#b0c4de</color><!--亮钢兰色 -->
    <color name="paleturquoise">#afeeee</color><!--苍宝石绿 -->
    <color name="greenyellow">#adff2f</color><!--黄绿色 -->
    <color name="lightblue">#add8e6</color><!--亮蓝色 -->
    <color name="darkgray">#a9a9a9</color><!--暗灰色 -->
    <color name="darkgrey">#a9a9a9</color><!--暗灰色 -->
    <color name="brown">#a52a2a</color><!--褐色 -->
    <color name="sienna">#a0522d</color><!--赭色 -->
    <color name="darkorchid">#9932cc</color><!--暗紫色 -->
    <color name="palegreen">#98fb98</color><!--苍绿色 -->
    <color name="darkviolet">#9400d3</color><!--暗紫罗兰色 -->
    <color name="mediumpurple">#9370db</color><!--中紫色 -->
    <color name="lightgreen">#90ee90</color><!--亮绿色 -->
    <color name="darkseagreen">#8fbc8f</color><!--暗海兰色 -->
    <color name="saddlebrown">#8b4513</color><!--重褐色 -->
    <color name="darkmagenta">#8b008b</color><!--暗洋红 -->
    <color name="darkred">#8b0000</color><!--暗红色 -->
    <color name="blueviolet">#8a2be2</color><!--紫罗兰蓝色 -->
    <color name="lightskyblue">#87cefa</color><!--亮天蓝色 -->
    <color name="skyblue">#87ceeb</color><!--天蓝色 -->
    <color name="gray">#808080</color><!--灰色 -->
    <color name="grey">#808080</color><!--灰色 -->
    <color name="olive">#808000</color><!--橄榄色 -->
    <color name="purple">#800080</color><!--紫色 -->
    <color name="maroon">#800000</color><!--粟色 -->
    <color name="aquamarine">#7fffd4</color><!--碧绿色 -->
    <color name="chartreuse">#7fff00</color><!--黄绿色 -->
    <color name="lawngreen">#7cfc00</color><!--草绿色 -->
    <color name="mediumslateblue">#7b68ee</color><!--中暗蓝色 -->
    <color name="lightslategray">#778899</color><!--亮蓝灰 -->
    <color name="lightslategrey">#778899</color><!--亮蓝灰 -->
    <color name="slategray">#708090</color><!--灰石色 -->
    <color name="slategrey">#708090</color><!--灰石色 -->
    <color name="olivedrab">#6b8e23</color><!--深绿褐色 -->
    <color name="slateblue">#6a5acd</color><!--石蓝色 -->
    <color name="dimgray">#696969</color><!--暗灰色 -->
    <color name="dimgrey">#696969</color><!--暗灰色 -->
    <color name="mediumaquamarine">#66cdaa</color><!--中绿色 -->
    <color name="cornflowerblue">#6495ed</color><!--菊兰色 -->
    <color name="cadetblue">#5f9ea0</color><!--军兰色 -->
    <color name="darkolivegreen">#556b2f</color><!--暗橄榄绿 -->
    <color name="indigo">#4b0082</color><!--靛青色 -->
    <color name="mediumturquoise">#48d1cc</color><!--中绿宝石 -->
    <color name="darkslateblue">#483d8b</color><!--暗灰蓝色 -->
    <color name="steelblue">#4682b4</color><!--钢兰色 -->
    <color name="royalblue">#4169e1</color><!--皇家蓝 -->
    <color name="turquoise">#40e0d0</color><!--青绿色 -->
    <color name="mediumseagreen">#3cb371</color><!--中海蓝 -->
    <color name="limegreen">#32cd32</color><!--橙绿色 -->
    <color name="darkslategray">#2f4f4f</color><!--暗瓦灰色 -->
    <color name="darkslategrey">#2f4f4f</color><!--暗瓦灰色 -->
    <color name="seagreen">#2e8b57</color><!--海绿色 -->
    <color name="forestgreen">#228b22</color><!--森林绿 -->
    <color name="lightseagreen">#20b2aa</color><!--亮海蓝色 -->
    <color name="dodgerblue">#1e90ff</color><!--闪兰色 -->
    <color name="midnightblue">#191970</color><!--中灰兰色 -->
    <color name="aqua">#00ffff</color><!--浅绿色 -->
    <color name="cyan">#00ffff</color><!--青色 -->
    <color name="springgreen">#00ff7f</color><!--春绿色 -->
    <color name="lime">#00ff00</color><!--酸橙色 -->
    <color name="mediumspringgreen">#00fa9a</color><!--中春绿色 -->
    <color name="darkturquoise">#00ced1</color><!--暗宝石绿 -->
    <color name="deepskyblue">#00bfff</color><!--深天蓝色 -->
    <color name="darkcyan">#008b8b</color><!--暗青色 -->
    <color name="teal">#008080</color><!--水鸭色 -->
    <color name="green">#008000</color><!--绿色 -->
    <color name="darkgreen">#006400</color><!--暗绿色 -->
    <color name="blue">#0000ff</color><!--蓝色 -->
    <color name="mediumblue">#0000cd</color><!--中兰色 -->
    <color name="darkblue">#00008b</color><!--暗蓝色 -->
    <color name="navy">#000080</color><!--海军色 -->
    <color name="black">#000000</color><!--黑色 -->
</resources>

项资源:activity_main.xml:

  <ListView
    android:id="@+id/lv_main_bookList"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

MainActivity:

//Android的逻辑页面

public class MainActivity extends AppCompatActivity {

private List<Book> data;
private MyBaseAdapter adapter;
private ListView lv_main_bookList;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lv_main_bookList = (ListView) findViewById(R.id.lv_main_bookList);

    this.data=new BookDao().list();
    adapter = new MyBaseAdapter((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE));
    lv_main_bookList.setAdapter(adapter);
}
public class MyBaseAdapter  extends BaseAdapter {
    public class ViewHolder{
        ImageView iv_listviewitem_image;
        TextView tv_listviewitme_title;
        TextView tv_listviewitme_author;
        TextView tv_listviewitme_price;
        TextView tv_listviewitme_publish;
        TextView tv_listviewitme_remark;


    }
    private LayoutInflater  inflater;


    public MyBaseAdapter(LayoutInflater inflater) {
        this.inflater = inflater;
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int i) {
        return data.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View v=view;
        if(v==null){
            ViewHolder vh=new ViewHolder();
            Log.i("test","position:"+i);
            v=inflater.inflate(R.layout.listview_item,null);
            vh.iv_listviewitem_image = (ImageView) v.findViewById(iv_listviewitem_image);
            vh.tv_listviewitme_title = (TextView) v.findViewById(R.id.tv_listviewitme_title);
            vh.tv_listviewitme_author = (TextView) v.findViewById(tv_listviewitme_author);
            vh.tv_listviewitme_price = (TextView) v.findViewById(tv_listviewitme_price);
            vh.tv_listviewitme_publish = (TextView) v.findViewById(tv_listviewitme_publish);
            vh.tv_listviewitme_remark = (TextView) v.findViewById(tv_listviewitme_remark);
            v.setTag(vh);
        }


        ViewHolder vh= (ViewHolder) v.getTag();
        Book book=data.get(i);
        vh.iv_listviewitem_image.setImageResource(book.getImage());
        vh.tv_listviewitme_title.setText(book.getTitle());
        vh.tv_listviewitme_author.setText(book.getAuthor());
        vh.tv_listviewitme_price.setText(book.getPrice()+"");
        vh.tv_listviewitme_publish.setText(book.getPublish());
        vh.tv_listviewitme_remark.setText(book.getRemark());
        return v;
    }
}

注:图片可在网上找些,修改逻辑类(BookDao)的图片名即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值