If I use create a ListView/ListAdapter and make use of convertView in the adapter's overridden getView() method, how are the properties of each list item view handled? Here's some code to better illustrate:
List Item
protected void onFinishInflate() {
super.onFinishInflate();
checkbox = (CheckedTextView)findViewById(android.R.id.text1);
description = (TextView)findViewById(R.id.description);
}
public void setTask(Task t) {
task = t;
checkbox.setText(t.getName());
checkbox.setChecked(t.isComplete());
if (t.getDescription().length() <= 0)
description.setVisibility(GONE);
else
description.setText(t.getDescription());
}
List Adapter
public View getView(int position, View convertView, ViewGroup parent) {
TaskListItem tli;
if (convertView == null)
tli = (TaskListItem)View.inflate(context, R.layout.task_list_ite开发者_StackOverflow中文版m, null);
else
tli = (TaskListItem)convertView;
tli.setTask(currentTasks.get(position));
return tli;
}
Whenever the list view gets refreshed (after it's initial appearance), every list item's TextView's visibility property gets set to "GONE." It took me a while to realize that the property was carrying over every time the view came from convertView. Explicitly setting the visibility property in both conditions solves the problem. Like so:
public void setTask(Task t) {
task = t;
checkbox.setText(task.getName());
checkbox.setChecked(task.isComplete());
if (task.getDescription().equals(""))
description.setVisibility(GONE);
else
description.setVisibility(VISIBLE);
description.setText(task.getDescription());
}
Is that because the recycled list item views don't get "reset" at all since they aren't being re-inflated? I feel like I understand this concept, but my grasp on it isn't as firm as I would like.
Is that because the recycled list item views don't get "reset" at all since they aren't being re-inflated?
Correct. Recycled really does mean "recycled" -- it is a row that had been on the screen, that you had configured for some other adapter position, and is now available for reuse. That row is however you left it, so you need to completely set it up, including possibly undoing things you had done to the row previously.
精彩评论