I am using this code to layout my ListView, using a different layout based on some data:
@Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
ViewHolder viewHolder;
MyInfo myInfo = getItem(i);
String label = myInfo.getLabel();
if (convertView == null) {
if (!"".equals(label)) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.info_grey, null);
Log.d(SapphireApplication.TAG, "GREY, label=" + label);
} else {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.info_plain, null);
Log.d(SapphireApplication.TAG, "PLAIN, label=" + label);
}
viewHolder = new ViewHolder();
viewHolder.tvLabel = convertView.findViewById(R.id.tvLabel);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder)convertView.getTag();
}
viewHolder.tvLabel.setText(label);
return convertView;
}
However, the Log.d is never done for some items in the list. Does that mean Android re-uses an existing convertView, causing it (in this case) to use the wrong layout?
Yes. They are being re-used. And that is the reason you are seeing that message log for few items only.
In this basic example however, all
convertViewsare similar. They were inflated from the same layout. This works fine for when you have a single view type per line. all items are similar but with different content. This still works if you have small differences. For example, you can inflate same layout and control the visibility of some of itsViewsaccording to the position (position 1 has an image and position 2 don't).However, there are some cases where you really need to inflate different layouts per row. For example, the "grey" layout is very different from the "plain" layout. On this case, you need to update you code as follows:
The most cool about theses concepts is that they are valid for any view that uses this View<->Adapter relation..
RecyclerView,ListView,Spinner,PagerViewetc.