当前位置:操作系统 > 安卓/Android >>

listView添加多个不同的adapter

有时候我们想在listView上分类,或者呢 有时候一行显示两列内容,有时候需要三列内容 ,那怎么实现呢,这里呢就要使用
Java代码 
class Section {   
        String caption;   
        Adapter adapter;   
           
        Section(String caption, Adapter adapter) {   
            this.caption=caption;   
            this.adapter=adapter;   
        }   
    }   
 
自定义一个类,这个类呢包含多个adapter就可以了,想用那种就用那种。
Java代码 
abstract public class SectionedAdapter extends BaseAdapter {   
    abstract protected View getHeaderView(String caption,int index,View convertView,ViewGroup parent);   
       
    private List<Section> sections=new ArrayList<Section>();   
    private static int TYPE_SECTION_HEADER=0;   
   
    public SectionedAdapter() {   
        super();   
    }   
   
    public void addSection(String caption, Adapter adapter) {   
        sections.add(new Section(caption, adapter));   
    }   
   
    public Object getItem(int position) {   
        for (Section section : this.sections) {   
            if (position==0) {   
                return(section);   
            }   
               
            int size=section.adapter.getCount()+1;   
   
            if (position<size) {   
                return(section.adapter.getItem(position-1));   
            }   
   
            position-=size;   
        }   
           
        return(null);   
    }   
   
    public int getCount() {   
        int total=0;   
           
        for (Section section : this.sections) {   
            total+=section.adapter.getCount()+1; // add one for header   
        }   
           
        return(total);   
    }   
   
    public int getViewTypeCount() {   
        int total=1;    // one for the header, plus those from sections   
           
        for (Section section : this.sections) {   
            total+=section.adapter.getViewTypeCount();   
        }   
           
        return(total);   
    }   
   
    public int getItemViewType(int position) {   
        int typeOffset=TYPE_SECTION_HEADER+1;   // start counting from here   
           
        for (Section section : this.sections) {   
            if (position==0) {   
                return(TYPE_SECTION_HEADER);   
            }   
               
            int size=section.adapter.getCount()+1;   
   
            if (position<size) {   
                return(typeOffset+section.adapter.getItemViewType(position-1));   
            }   
   
            position-=size;   
            typeOffset+=section.adapter.getViewTypeCount();   
        }   
           
        return(-1);   
    }   
   
    public boolean areAllItemsSelectable() {   
        return(false);   
    }   
   
    public boolean isEnabled(int position) {   
        return(getItemViewType(position)!=TYPE_SECTION_HEADER);   
    }   
   
    @Override   
    public View getView(int position, View convertView,   
                      &nb

补充:移动开发 , Android ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,