Reputation: 273
I've implemented a custom ArrayAdapter which all seems to work fine however whenever I add a new item to the adapter and scroll the list, the text within the text view seems's to change except for the first TextView.
I've also used the ViewHolder pattern but it's still not working correctly:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.subject_row, null);
holder = new ViewHolder();
holder.subjectName = (TextView) view.findViewById(R.id.subject_name);
holder.task1 = (TextView) view.findViewById(R.id.tasks1);
holder.task2 = (TextView) view.findViewById(R.id.tasks2);
holder.task3 = (TextView) view.findViewById(R.id.tasks3);
holder.time = (TextView) view.findViewById(R.id.time);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
Subject subject = getItem(position);
ArrayList<Task> tasks = subject.getTasks();
int numTask = tasks.size();
holder.subjectName.setText(subject.getSubjectName());
holder.time.setText(subject.getHours() + " hrs " + subject.getMins() + " mins");
switch (numTask) {
case 0: {
holder.task1.setVisibility(View.GONE);
holder.task2.setVisibility(View.GONE);
holder.task3.setVisibility(View.GONE);
break;
}
case 1: {
holder.task1.setText(tasks.get(0).getDescription());
holder.task2.setVisibility(View.GONE);
holder.task3.setVisibility(View.GONE);
break;
}
case 2: {
holder.task1.setText(tasks.get(0).getDescription());
holder.task2.setText(tasks.get(1).getDescription());
holder.task3.setVisibility(View.GONE);
break;
}
case 3: {
holder.task1.setText(tasks.get(0).getDescription());
holder.task2.setText(tasks.get(1).getDescription());
holder.task3.setText(tasks.get(2).getDescription());
break;
}
}
return view;
}
The first textview with the subject name does not appear to change, however the data within the other 3 textviews' () is also showing data from other rows.
It may be something to do with hiding its view if the data is blank but if removed the switch statement and still get the same result.
Thanks.
Upvotes: 0
Views: 130
Reputation: 51
Below post has clear explanation on adding dynamic content and preserving state. Hope it helps.
http://sgandroiddev.blogspot.com/2013/02/custom-listview.html
Upvotes: 0
Reputation: 86948
You aren't making the hidden Views visible again, for instance:
case 1: {
holder.task1.setVisibility(View.VISIBLE); // Add these!
holder.task1.setText(tasks.get(0).getDescription());
holder.task2.setVisibility(View.GONE);
holder.task3.setVisibility(View.GONE);
break;
}
Upvotes: 1
Reputation: 393
I think you have to "write back" the holder into the view.
view.setTag(holder);
But I don't understand why you use a holder-class. I think, you don't need this! Just use
TextView subjectName = view.findViewById(R.id.subjectName);
subjectName.setText(...);
Upvotes: 0