[英]Android ListView - divider after nth element
I need to place a divider after nth element in the list view that is generated from a mysqli cursor. 我需要在由mysqli游标生成的列表视图中的第n个元素之后放置一个分隔符。 I created custom adapter that tries to do that, like this: 我创建了尝试执行此操作的自定义适配器,如下所示:
MyAdapter extends CursorAdapter {
...
blablabla
yadayadayada
...
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final View view;
int pos = cursor.getPosition();
int beforeLast = GameData.totalPlayers-1;
if (pos == beforeLast) {
view = mInflater.inflate(R.layout.player_details_divider, parent, false);
} else {
view = mInflater.inflate(R.layout.player_details, parent, false);
}
return view;
}
}
So as you can see its supposed to inflate different view for an element on a position totalPlayers-1. 因此,正如您所看到的,它应该为位置totalPlayers-1上的元素增加不同的视图。 It works great when number is small enough: 1 through 6. But when its bigger it just stops working. 当数字足够小(1到6)时,它会很好用。但是,当数字更大时,它就会停止工作。
I tried debugging the thing and I noticed that it renders 6 items - this is how much list elements fits on the screen - and goes through the loop 6 times incrementing pos to 5. Then it stops. 我尝试调试该东西,然后发现它呈现了6个项目(这是屏幕上适合放置的列表元素的数量),并经过6次循环,将pos递增到5。然后停止。 When I start scrolling the list, it runs the loop again, incrementing pos to 6 and then it stops. 当我开始滚动列表时,它将再次运行循环,将pos递增至6,然后停止。 No matter how many elements there are it just never increments pos to 7 (although all data are present in the list, so cursor must be iterated to the end). 不管有多少个元素,它都永远不会将pos递增到7(尽管列表中存在所有数据,所以必须将游标迭代到最后)。
Any ideas why it behaves like this? 任何想法为什么它会这样? What is it I am not understanding/doing wrong? 我没有理解/做错什么?
Issue seems to be due to the ListView
recycle. 问题似乎是由于ListView
回收。 ListView
will try to reuse the same view for the items. ListView
将尝试为项目重复使用相同的视图。 So in your case , newView
is called for first 6 visible items and when you scroll ListView
resizes the same 6 items views for the next 6 item in the list. 因此,在您的情况下, newView
前6个可见项调用newView
,并且在滚动ListView
时,将为列表中的下6个项调整相同的6个视图的大小。
You need to update the ListView
, that you have 2 different item view, so that it know your last item views is different from others 您需要更新ListView
,您有2个不同的项目视图,以便它知道您的最后一个项目视图与其他视图不同
You need to override
the getViewTypeCount
and return that you have 2 different view 您需要override
getViewTypeCount
并返回您有2个不同的视图
@Override
public int getViewTypeCount() {
return 2; // return the view type
}
Also, override
getItemViewType
and inform ListView
that the last position view
is the one different. 另外, override
getItemViewType
并通知ListView
last position view
是一个不同的last position view
。
Override
public int getItemViewType(int position){
int beforeLast = GameData.totalPlayers-1;
// return a unique number
if(beforeLast == position) {
return 1; // some unique id
}else {
return 0;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.