文档章节

HowTo: ListView, Adapter

artshell
 artshell
发布于 2014/09/27 21:44
字数 615
阅读 34
收藏 1
点赞 0
评论 0

I was surprised that getViewTypeCount() is so rarely overrided. If you are an expert in this – this post is not for you)

ListView and Adapter Basics

How it works:

1、ListView asks adapter “give me a view” (getView) for each item of the list
2、A new View is returned and displayed
Next question – what if we have one billion items? Create new view for each item? The answer is NO,Android caches views for you.

There’s a component in Android called “Recycler”.

1、If you have 1 billion items – there are only visible items in the memory + view in recycler.
2、ListView asks for a view type1 first time (getView) x visible items. convertView is null in getView – you create new view of type1 and return it.
3、ListView asks for a view type1 when one item1 is outside of the window and new item the same type is comming from the bottom. convertView is not null = item1. You should just set new data and return convertView back. No need to create view again.
Let’s write a simple code and put System.out to the getView:

public class MultipleItemsList extends ListActivity {
 
    private MyCustomAdapter mAdapter;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAdapter = new MyCustomAdapter();
        for (int i = 0; i < 50; i++) {
            mAdapter.addItem("item " + i);
        }
        setListAdapter(mAdapter);
    }
 
    private class MyCustomAdapter extends BaseAdapter {
 
        private ArrayList mData = new ArrayList();
        private LayoutInflater mInflater;
 
        public MyCustomAdapter() {
            mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
 
        public void addItem(final String item) {
            mData.add(item);
            notifyDataSetChanged();
        }
 
        @Override
        public int getCount() {
            return mData.size();
        }
 
        @Override
        public String getItem(int position) {
            return mData.get(position);
        }
 
        @Override
        public long getItemId(int position) {
            return position;
        }
 
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            System.out.println("getView " + position + " " + convertView);
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item1, null);
                holder = new ViewHolder();
                holder.textView = (TextView)convertView.findViewById(R.id.text);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder)convertView.getTag();
            }
            holder.textView.setText(mData.get(position));
            return convertView;
        }
 
    }
 
    public static class ViewHolder {
        public TextView textView;
    }
}


Different list items' layouts

Let’s move to the “more complicated” example. How about to add separator somewhere to the list.

You should do the following:

1、Override getViewTypeCount() – return how many different view layouts you have
2、Override getItemViewType(int) – return correct view type id by position
3、Create correct convertView (depending on view item type) in getView
Simple, isn’t it? Code snippet:

public class MultipleItemsList extends ListActivity {
 
    private MyCustomAdapter mAdapter;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAdapter = new MyCustomAdapter();
        for (int i = 1; i < 50; i++) {
            mAdapter.addItem("item " + i);
            if (i % 4 == 0) {
                mAdapter.addSeparatorItem("separator " + i);
            }
        }
        setListAdapter(mAdapter);
    }
 
    private class MyCustomAdapter extends BaseAdapter {
 
        private static final int TYPE_ITEM = 0;
        private static final int TYPE_SEPARATOR = 1;
        private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;
 
        private ArrayList mData = new ArrayList();
        private LayoutInflater mInflater;
 
        private TreeSet mSeparatorsSet = new TreeSet();
 
        public MyCustomAdapter() {
            mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
 
        public void addItem(final String item) {
            mData.add(item);
            notifyDataSetChanged();
        }
 
        public void addSeparatorItem(final String item) {
            mData.add(item);
            // save separator position
            mSeparatorsSet.add(mData.size() - 1);
            notifyDataSetChanged();
        }
 
        @Override
        public int getItemViewType(int position) {
            return mSeparatorsSet.contains(position) ? TYPE_SEPARATOR : TYPE_ITEM;
        }
 
        @Override
        public int getViewTypeCount() {
            return TYPE_MAX_COUNT;
        }
 
        @Override
        public int getCount() {
            return mData.size();
        }
 
        @Override
        public String getItem(int position) {
            return mData.get(position);
        }
 
        @Override
        public long getItemId(int position) {
            return position;
        }
 
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            int type = getItemViewType(position);
            System.out.println("getView " + position + " " + convertView + " type = " + type);
            if (convertView == null) {
                holder = new ViewHolder();
                switch (type) {
                    case TYPE_ITEM:
                        convertView = mInflater.inflate(R.layout.item1, null);
                        holder.textView = (TextView)convertView.findViewById(R.id.text);
                        break;
                    case TYPE_SEPARATOR:
                        convertView = mInflater.inflate(R.layout.item2, null);
                        holder.textView = (TextView)convertView.findViewById(R.id.textSeparator);
                        break;
                }
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder)convertView.getTag();
            }
            holder.textView.setText(mData.get(position));
            return convertView;
        }
 
    }
 
    public static class ViewHolder {
        public TextView textView;
    }
}




本文转载自:http://android.amberfog.com/?p=296

共有 人打赏支持
artshell
粉丝 2
博文 56
码字总数 5163
作品 0
成都
程序员
Fragment中嵌入两个listview,从该fragment切换另外的fragment时闪退

初学者,请各位大神指点 //从该fragment切出时闪退 public class MainBottomMe extends Fragment { private List meListViewperset = new ArrayList<>(); / private List meListViewsetting......

jeffblink ⋅ 2017/06/12 ⋅ 0

解决listview出现线程更新错误问题

java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a......

MrLovelyCbb ⋅ 2011/12/09 ⋅ 1

Android listview addHeaderView 和 addFooterView 详解

addHeaderView()方法:主要是向listView的头部添加布局 addFooterView()方法:主要是向listView的底部添加布局 需要注意的是添加布局的时候应该添加从父容器开始添加,而不能直接添加父容器中...

程序袁_绪龙 ⋅ 2015/08/05 ⋅ 2

《每日一剂》适配器刷新报错adapter.notifyDataSetChanged()解决

在使用ListView过程中,有时会出现The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a ......

王先森oO ⋅ 05/29 ⋅ 0

android listview addHeaderView和addFooterView的注意事项

今天在做项目的时候用了自定义listview以及自定义的item、adapter。现在把其中需要注意的地方记录下来: 1、item内如果有button等控件时,在监听listview的onitemclick事件时,焦点会被item内...

等待流星 ⋅ 2014/03/14 ⋅ 0

ListView嵌套ListView缓存失效问题

ListView嵌套ListView缓存失效问题 Android中在写列表的时候,相信很多时候,我们都需要进行ListView嵌套ListView编程。比如说:帖子+评论页面的编写。然而这种模型是会出现被嵌套ListView缓...

精通吹水 ⋅ 2016/03/20 ⋅ 0

即时通讯发消息出现ListView左边视图突然闪现,再加载右边视图的bug

刚开始发送一条消息是这样处理的: conversation.addMessage(message); listView.setAdapter(adapter); adapter.refreshSelectLast(); 使得ListView刷新了2次,其中listView.setAdapter(ada......

xunfang ⋅ 2016/01/22 ⋅ 0

Android 给RecyclerView添加头部和尾部

之前我在GitHub上开源了一个可以实现RecyclerView列表分组的通用Adapter: GroupedRecyclerViewAdapter。也在博客上写了一篇专门介绍它的实现和使用的文章:《Android 可分组的RecyclerViewA...

donkingliang ⋅ 2017/11/13 ⋅ 0

android中listview的getView方法不调用的一种情况

1,我的ListView是放在一个ScrollView中的,listView中加了一个HeaderView(头布局)。大家都知道在ScrolleView中使用ListView需要计算listview每个item的高度,不然的话,listview只会显示一个...

宇宙执政 ⋅ 2013/12/06 ⋅ 0

android使用notifyDataSetChanged()方法,listview数据没有更新

android使用notifyDataSetChanged()方法,发现adapter的数据更新了,但是ListView的内容没有更新? 查阅如下网站解决方案都没有解决: http://blog.csdn.net/williamz1980/article/details/5...

青莲居士 ⋅ 2015/07/21 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

Day 17 vim简介与一般模式介绍

vim简介 vi和Vim的最大区别就是编辑一个文件时vi不会显示颜色,而Vim会显示颜色。显示颜色更便于用户编辑,凄然功能没有太大的区别 使用 yum install -y vim-enhanced 安装 vim的三种常用模式...

杉下 ⋅ 54分钟前 ⋅ 0

【每天一个JQuery特效】根据可见状态确定是否显示或隐藏元素(3)

效果图示: 主要代码: <!DOCTYPE html><html><head><meta charset="UTF-8"><title>根据可见状态确定 是否显示或隐藏元素</title><script src="js/jquery-3.3.1.min.js" ty......

Rhymo-Wu ⋅ 今天 ⋅ 0

OSChina 周四乱弹 —— 初中我身体就已经垮了,不知道为什么

Osc乱弹歌单(2018)请戳(这里) 【今日歌曲】 @加油东溪少年 :下完这场雨 后弦 《下完这场雨》- 后弦 手机党少年们想听歌,请使劲儿戳(这里) @马丁的代码 :买了日本 日本果然赢了 翻了...

小小编辑 ⋅ 今天 ⋅ 12

浅谈springboot Web模式下的线程安全问题

我们在@RestController下,一般都是@AutoWired一些Service,由于这些Service都是单例,所以并不存在线程安全问题。 由于Controller本身是单例模式 (非线程安全的), 这意味着每个request过来,...

算法之名 ⋅ 今天 ⋅ 0

知乎Java数据结构

作者:匿名用户 链接:https://www.zhihu.com/question/35947829/answer/66113038 来源:知乎 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 感觉知乎上嘲讽题主简...

颖伙虫 ⋅ 今天 ⋅ 0

Confluence 6 恢复一个站点有关使用站点导出为备份的说明

推荐使用生产备份策略。我们推荐你针对你的生产环境中使用的 Confluence 参考 Production Backup Strategy 页面中的内容进行备份和恢复(这个需要你备份你的数据库和 home 目录)。XML 导出备...

honeymose ⋅ 今天 ⋅ 0

JavaScript零基础入门——(九)JavaScript的函数

JavaScript零基础入门——(九)JavaScript的函数 欢迎回到我们的JavaScript零基础入门,上一节课我们了解了有关JS中数组的相关知识点,不知道大家有没有自己去敲一敲,消化一下?这一节课,...

JandenMa ⋅ 今天 ⋅ 0

火狐浏览器各版本下载及插件httprequest

各版本下载地址:http://ftp.mozilla.org/pub/mozilla.org//firefox/releases/ httprequest插件截至57版本可用

xiaoge2016 ⋅ 今天 ⋅ 0

Docker系列教程28-实战:使用Docker Compose运行ELK

原文:http://www.itmuch.com/docker/28-docker-compose-in-action-elk/,转载请说明出处。 ElasticSearch【存储】 Logtash【日志聚合器】 Kibana【界面】 答案: version: '2'services: ...

周立_ITMuch ⋅ 今天 ⋅ 0

使用快嘉sdkg极速搭建接口模拟系统

在具体项目研发过程中,一旦前后端双方约定好接口,前端和app同事就会希望后台同事可以尽快提供可供对接的接口方便调试,而对后台同事来说定好接口还仅是个开始、设计流程,实现业务逻辑,编...

fastjrun ⋅ 今天 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部