文档章节

HowTo: ListView, Adapter

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

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
60
0
《每日一剂》适配器刷新报错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
0
Android listview addHeaderView 和 addFooterView 详解

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

程序袁_绪龙
2015/08/05
0
2
ListView嵌套ListView缓存失效问题

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

精通吹水
2016/03/20
120
0
android listview addHeaderView和addFooterView的注意事项

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

等待流星
2014/03/14
0
0

没有更多内容

加载失败,请刷新页面

加载更多

OSChina 周一乱弹 —— 鱼生不值得

Osc乱弹歌单(2018)请戳(这里) 【今日歌曲】 @瘟神灬念:分享新裤子的单曲《没有理想的人不伤心 (Remix版)》: 《没有理想的人不伤心 (Remix版)》- 新裤子 手机党少年们想听歌,请使劲儿戳...

小小编辑
51分钟前
59
7
arts-week10

Algorithm 905. Sort Array By Parity - LeetCode Review Who’s Afraid of the Big Bad Preloader? 一文读懂前端缓存 一个网络请求3个步骤:请求,处理,响应,而前端缓存主要在请求处响应这两步...

yysue
今天
5
0
00.编译OpenJDK-8u40的整个过程

前言 历经2天的折腾总算把OpenJDK给编译成功了,要说为啥搞这个,还得从面试说起,最近出去面试经常被问到JVM的相关东西,总感觉自己以前学的太浅薄,所以回来就打算深入学习,目标把《深入理...

凌晨一点
今天
6
1
python: 一些关于元组的碎碎念

初始化元组的时候,尤其是元组里面只有一个元素的时候,会出现一些很蛋疼的情况: def checkContentAndType(obj): print(obj) print(type(obj))if __name__=="__main__": tu...

Oh_really
昨天
7
2
jvm crash分析工具

介绍一款非常好用的jvm crash分析工具,当jvm挂掉时,会产生hs_err_pid.log。里面记录了jvm当时的运行状态以及错误信息,但是内容量比较庞大,不好分析。所以我们要借助工具来帮我们。 Cras...

xpbob
昨天
197
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部