An SO User
An SO User

Reputation: 24998

My ListView has two types of views. How to manage?

My events management app has two types of views in the list view : a small simmple text view for not-so-important events and a complex view created with a FrameLayout.

in the onCreateView() of the adapter, I return these views depending upon the nature of the event.

if(convertView == null){
  if(important)
   // inflate the complex view
  else
   // inflate the simpler view
}  

This is all good when convertView is null. Due to the view recycling in Android, it may happen that the convertView returned to me is recycled from the simpler view and I now have to display the larger view. One dumb solution is to inflate new views all the time. However, this will kill performance.

Another way is to have invisible TextViews in both of them (visibility=gone) with predefined values and depending on what value is in them, I can inflate the views. To me, this seems like a hack rather than a real solution.

What is the right way to handle this situation?

Upvotes: 1

Views: 492

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006644

Due to the view recycling in Android, it may happen that the convertView returned to me is recycled from the simpler view and I now have to display the larger view.

Not if you override getViewTypeCount() and getItemViewType() in your adapter.

In your case:

  • getViewTypeCount() would return 2

  • getItemViewType() would return 0 or 1, where you return 0 for those positions that are one type of row, and return 1 for those positions that return the other type of row

Then, you are guaranteed that if convertView is not null, it is a row of the proper type.

Upvotes: 6

Related Questions