Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

android - Recycling views in custom array adapter: how exactly is it handled?

I am having an unclear issue concerning the recycling of views in a getView method of a custom array adapter.

I understand that elements are reused, but how do I know exact what to implement in the first part of the if statement, and what in the second?

Right now I am having following code. I came to this question due to dropping the code in the second part of the statement which results in a list of the first 9 elements, which are repeated numberous times instead of all elements. I didn't really know what is causing this exactly...

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

        if (row == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);

            title = getItem(position).getTitle();
            size = calculateFileSize(position);

            txtTitle = (TextView) row.findViewById(R.id.txtTitle);
            tvFileSize = (TextView) row.findViewById(R.id.tvFileSize);

            txtTitle.setText(title);
            tvFileSize.setText(size);

        } else {

            title = getItem(position).getTitle();
            size = calculateFileSize(position);

            txtTitle = (TextView) row.findViewById(R.id.txtTitle);
            tvFileSize = (TextView) row.findViewById(R.id.tvFileSize);

            txtTitle.setText(title);
            tvFileSize.setText(size);
        }

        return row;
    } 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's easy. The first time no row is created, so you have to inflate them. Afterwards, the Android os may decide to recycle the views that you already inflated and that are not visible anymore. Those are already inflated and passed into the convertView parameter, so all you have to do is to arrange it to show the new current item, for example placing the right values into the various text fields.

enter image description here

In short, in the first part you should perform the inflation AND fill the values, in the second if (if convertView != null) you should only overwrite the field because, given the view has been recycled, the textviews contain the values of the old item.

This post and this are good starting points


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...