考虑以下示例,在重写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;
}
}
答案 0 :(得分:1)
由于您没有创建新视图并在向下滚动时使用旧视图(此时convertView不会为null)
尝试这种方式它会正确
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return super.getView(position, convertView, parent);
}
你需要这样做(在这里使用convertview),因为ArrayAdapter已经具有相同的逻辑
来自widget / 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;
}
答案 1 :(得分:0)
如果您使用Custom 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();