Reputation: 2913
So I am attempting to set a different layout resource for my first ListItem element using this code:
int type;
@Override
public int getItemViewType(int position) {
if(position==0) {
type = R.layout.queue_item_next;
} else {
type = R.layout.queue_item;
}
return type;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = (View) inflater.inflate(getItemViewType(position), parent, false);
}
This code works however with some unexpected behavior. For some reason the last element of the ListView is also being set to have this alternate layout and I have no idea why.
What could cause this to happen?
Thanks.
Upvotes: 0
Views: 55
Reputation: 2502
Issue is coming due getItemViewType() is returning value greater than number of view types. You can use bellow code working perfectly fine for me.
@Override
public int getItemViewType(int position) {
if(position==0) {
return 0;
}
return 1;
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int type = getItemViewType(position);
if(type == 0)
convertView = (View) inflater.inflate(R.layout.first_layout, parent, false);
else
convertView = (View) inflater.inflate(R.layout.second_layout, parent, false);
}
}
Note : If only first view is different then best option is to use headerView using function listview.addHeaderView() function using this link
Upvotes: 2
Reputation: 1422
because you are using if(convertView == null) {}
that means if previous view is available in memory use that one else create a new one. So, sometimes on scroll fast/slow depends on resources available of phone it varies.
to solve this problem dont check if(convertView == null)
use like this
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = (View) inflater.inflate(getItemViewType(position), parent, false);
}
Upvotes: 0