Android GridView,回收两个不同的单元格?

时间:2016-11-29 17:43:05

标签: android android-gridview

我有一个GridView。它总是两列。

对于仅在顶部的前两个单元格,我有一个不同的单元格。

在Apdater中,我这样做......

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    if (position<2) {
        // just return a new header cell - no need to try to be efficient,
        // there are only ever two of the header cells
        convertView = LayoutInflater.from(c).inflate(R.layout.cell_header, null);
        return convertView;
        // you're completely done
    }

    // from here, we want only a normal cell...

    if (convertView == null) {
        // just make a new one
        convertView = LayoutInflater.from(c).inflate(R.layout.d.cell_normal, null);
    }

    // if you get to here, there's a chance it's giving us a header cell to recycle,
    // if so get rid of it

    int id = convertView.getId();
    if (id == R.id.id_cell_header) {
        Log.d("DEV", "We got a header cell in recycling - dump it");
        convertView = LayoutInflater.from(c).inflate(R.layout.cell_normal, null);
    }

    ... populate the normal cell in the usual way

    return convertView;
    }

这很有效。注意我只是不回收标题单元格。没问题,因为只有两个。

但是如果你想要一个有两个完全不同的单元格的GridView呢? (想象一下GridView,每种类型的50个,都混合在一起。)

我的意思是,两者大小相同,但它们完全不同,两个不同的xml文件,完全不同的布局?

你如何“同时回收”?

与此有什么关系?

1 个答案:

答案 0 :(得分:1)

不想回答我自己的问题,但是

感谢总是令人惊叹的CommonsWare!...

这就是你如何做到的:

@Override
public int getViewTypeCount() {
    // we have two different types of cells, so return that number
    return 2;
}

@Override
public int getItemViewType(int position) {
    if (..position should be a header-type cell..)
        return 1;       // 1 means to us "header type"
    else
        return 0;       // 0 means to us "normal type"
    // note the 0,1 are "our own" arbitrary index.
    // you actually don't have to use that index again: you're done.
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        if ( ..position should be a header-type cell.. )
            convertView = LayoutInflater.from(c).inflate(R.layout.cell_header, null);
        else
            convertView = LayoutInflater.from(c).inflate(R.layout.cell_normal, null);
    }

    if ( ..position should be a header-type cell.. ) {
        // .. populate the header type of cell ..
        // .. it WILL BE a header type cell ..
    }
    else {
        // .. populate the normal type of cell ..
        // .. it WILL BE a normal type cell ..
    }

    return convertView;
}

这是&#34; Good Android&#34; ......漂亮,可爱的东西。