views:

46

answers:

2

Hi, I am creating a scrolling panel with many child views (e.g. buttons). Each child view has a fixed location based on their row and column index. I cannot create them at the beginning since there are tons of them and I will run out of memory, so I'd like to only add a child view when it intersects with the screen view port (when users scrolls to that area). I override the onLayout() method with something like this:

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    super.onLayout(changed, l, t, r, b);
    for (int row = 0; row < ROW_NUM; row++) {
        ColumnAdapter columnAdapter = mRowAdapter.getItem(row);
        for (int col = 0; col < COLUMN_NUM; col++) {
            ItemView itemView = columnAdapter.getView(col, null, this);
            if (isOnScreen(row, col)) {
                itemView.layout(col * 100, row * 100, (col + 1) * 100, (row + 1) * 100);
                addViewInLayout(itemView, row + col, null, true);
            }
        }
    }
    scrollTo(getScrollX(), getScrollY());
}

(ColumnAdapter is an Adapter extension and ItemView is button extension). This wouldn't work because onLayout() is not called during scrolling. What should I do to add ItemViews dynamically as user scrolls?

A: 

Never mind I figured that you can use requestLayout()...

Rachel Z
A: 

You may also want to consider using a ListView. It does exactly what you want, that is a lazy load of its elements. See the Google IO session on ListView for details.

In short, the Adapter class you are extending has a View getView(int position, View convertView, ViewGroup parent) function. This function can be overriden and doing a check to see if convertView is not null and loading that since it is actually a previously created View of that child element.

There are also additional details on avoiding the findViewById() function call since it is expensive.

Noel
Hi Noel, thanks for the response. I'd love to use ListView except for the widget I'm creating contains many columns that can scroll together, while ListView handles their own scrolling individually.
Rachel Z