首页 > 代码库 > HowTo: ListView, Adapter

HowTo: ListView, Adapter

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 = http://www.mamicode.com/new ArrayList();> 


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 = http://www.mamicode.com/new ArrayList();> 




HowTo: ListView, Adapter