0

考虑以下示例,列表项的顺序在重写 getView() 方法之前是正确的。每当我重写它以完成一些额外的工作(示例中未显示)时,项目的顺序就会变得一团糟。我向下滚动以查看一个数字,然后向上滚动以再次查看相同的数字。这种奇怪行为的原因是什么,我该如何解决?

package com.staticlist;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

public class MainActivity extends ListActivity {
    String[] items = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16",
            "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33",
            "34", "35", "36", "37", "38", "39", "40" };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setListAdapter(new MyListAdapter(this, R.layout.main, items));
    }
}

class MyListAdapter extends ArrayAdapter<String> {
    public MyListAdapter(MainActivity mainActivity, int main, String[] items) {
        super(mainActivity, main, items);
    }

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

        if (convertView == null) {
            row = super.getView(position, convertView, parent);
        } else {
            row = convertView;
        }

        return row;
    }
}
4

2 回答 2

1

由于您在向下滚动时没有创建新视图并使用旧视图(当时 convertView 不会为空)

试试这个方法它会正确的

@Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return super.getView(position, convertView, parent);
    }

您需要这样做(在此处使用 convertview),因为 ArrayAdapter 已经具有相同的逻辑

来自小部件/ ArrayAdapter.java

public View getView(int position, View convertView, ViewGroup parent) {
        return createViewFromResource(position, convertView, parent, mResource);
    }

    private View createViewFromResource(int position, View convertView, ViewGroup parent,
            int resource) {
        View view;
        TextView text;

        if (convertView == null) {
            view = mInflater.inflate(resource, parent, false);
        } else {
            view = convertView;
        }

https://github.com/android/platform_frameworks_base/blob/master/core/java/android/widget/ArrayAdapter.java

于 2012-06-27T12:23:24.617 回答
0

在您的情况下,如果您使用自定义 ArrayAdapter,则需要添加以下内容。

adapter.sort(new Comparator<String>() {

            @Override
            public int compare(String lhs, String rhs) {
                if (Integer.parseInt(lhs) == Integer.parseInt(rhs))
                    return 0;
                else if (Integer.parseInt(lhs) > Integer.parseInt(rhs))
                    return 1;
                else
                    return -1;
            }
        });
adapter.notifyDataSetChanged();
于 2012-06-27T13:08:54.580 回答