在我的自定义 ListAdapter 中,第一次调用 GetView() 时,convertView 作为 NULL 传入,但第二次作为第一次创建的 View 传入。我的 ListView 有 4 行,所有 4 行同时出现在屏幕上。从文档来看,似乎 convertView 应该是一个已经创建并且现在已经滚出屏幕的 View 。我希望 convertView 全部 4 次都为 null,以便它会创建/膨胀 4 个单独的 View 。我应该在第一次调用 getView 后有一个 convertView 吗?谢谢。
在 OnCreate() 中:
Cursor questions = db.loadQuestions(b.getLong("categoryId"), inputLanguage.getLanguageId(), outputLanguage.getLanguageId());
startManagingCursor(questions);
ListAdapter adapter = new QuestionsListAdapter(this, questions);
ListView list = (ListView)findViewById(R.id.list1);
setListAdapter(adapter);
适配器类
private class QuestionsListAdapter extends BaseAdapter implements ListAdapter{
private Cursor c;
private Context context;
public QuestionsListAdapter(Context context, Cursor c) {
this.c = c;
this.context = context;
}
public Object getItem(int position) {
c.moveToPosition(position);
return new Question(c);
}
public long getItemId(int position) {
c.moveToPosition(position);
return new Question(c).get_id();
}
@Override
public int getItemViewType(int position) {
Question currentQuestion = (Question)this.getItem(position);
if (currentQuestion.getType().equalsIgnoreCase("text"))
return 0;
else if (currentQuestion.getType().equalsIgnoreCase("range"))
return 0;
else if (currentQuestion.getType().equalsIgnoreCase("yesNo"))
return 2;
else if (currentQuestion.getType().equalsIgnoreCase("picker"))
return 0;
else if (currentQuestion.getType().equalsIgnoreCase("command"))
return 0;
else if (currentQuestion.getType().equalsIgnoreCase("datePicker"))
return 0;
else if (currentQuestion.getType().equalsIgnoreCase("diagram"))
return 0;
else
return -1;
}
@Override
public int getViewTypeCount() {
return 7;
}
public int getCount() {
return c.getCount();
}
public View getView(int position, View convertView, ViewGroup viewGroup) {
Question currentQuestion = (Question)this.getItem(position);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.question_row_text, null);
}
//setup cell
return convertView;
}
}
最佳答案
如果我没记错的话,GetView
将为要显示的每一行调用两次。我认为第一组调用是为了布局目的而完成的,第二组返回将实际显示的 View 。第二组调用应该返回与第一组调用相同的 View ,这是有道理的。
在任何情况下,您的代码都不应该关心它是被调用用于布局还是显示。在几乎所有情况下,如果 convertView
不为空,那么通常应该返回 convertView
;否则,您应该返回一个新 View 。
关于android - ConvertView 作为仍在屏幕上的 View 传入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6272193/