当我尝试在具有多个自定义布局的 ListView 中重用视图时,会出现问题。当我更改项目数量时,我得到错误的 convertView 被传递给 getView 方法。详细说明:我有一个页眉布局、一个行布局和一个页脚布局。在标题中,我可以更改行数。1 行的示例:页眉 row1 页脚 当我重用视图时,我得到错误的结果(添加另一行后)。发生这种情况是因为先前创建的页脚视图是为 position = 2 传递的,并且由于它不是 null 我不重新创建它: Header row1 Footer Footer
而不是预期:标题 row1 row2 页脚
我究竟做错了什么?还是设计使然,我应该重新创建视图而不是重用它们?这是我的代码:
public class NewProgramAdapter extends BBBaseAdapter {
public static int TYPE_HEADER = 1;
public static int TYPE_FORM = 2;
public static int TYPE_FOOTER = 3;
protected String mDays;
protected String mProgramId;
protected int currentDay = 0;
protected int numberOfExercises = 1;
protected JSONArray items = new JSONArray();
public NewProgramAdapter(Activity a) {
super(a);
// TODO Auto-generated constructor stub
}
@Override
public int getCount() {
return numberOfExercises + 2; // header and footer
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (position > 0 && position < getCount() - 1) {
return getFormView(position, convertView, parent);
} else if (position == 0) {
return getHeaderView(position, convertView, parent);
} else {
return getFooterView(position, convertView, parent);
}
}
private View getFooterView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = mA.getLayoutInflater();
v = inflater.inflate(R.layout.new_exercise_footer, null);
}
return v;
}
private View getHeaderView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = mA.getLayoutInflater();
v = inflater.inflate(R.layout.new_exercise_header, null);
Spinner sp = (Spinner) v.findViewById(R.id.spinnerExercises);
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView,
View selectedItemView, int position, long id) {
int n = position + 1;
setNumberOfExercises(n);
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
}
return v;
}
private View getFormView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = mA.getLayoutInflater();
v = inflater.inflate(R.layout.new_exercise_form, null);
}
return v;
}
@Override
public int getItemViewType(int position) {
if (position > 0 && position < getCount() - 1) {
return TYPE_FORM;
} else if (position == 0) {
return TYPE_HEADER;
} else {
return TYPE_FOOTER;
}
}
@Override
public void updateEntries(Object data) {
items = (JSONArray) data;
notifyDataSetChanged();
}
public void next() {
currentDay++;
notifyDataSetChanged();
}
public void setNumberOfExercises(int n) {
numberOfExercises = n;
notifyDataSetChanged();
}
public void setDays(String string) {
mDays = string;
}
public void setProgramId(String string) {
mProgramId = string;
}
}