listview 翻页功能简单实现
#include<stdio.h>
typedef struct _scroll_
{
int top;
int cur;
int page;
int count;
}scroll,*p_scroll;
/*
支持按单步移动和按页移动
如果单步触发了翻页,整页向上/下移动一步
如果换页触发了翻页,整页移动到下一页/上一页
*/
void adjust_scroll(p_scroll scroll ,int len);
//测试
int main(int argc,char *argv[])
{
int step=0;
scroll sl = {0,0,10,23};
if(argc > 1)
{
sl.count = atoi(argv[1]);
printf("count:%d\n",sl.count);
}
while(1)
{
scanf("%d",&step);//step 值为1/-1/page/-page
if((step != 1) && (step != -1) && (step != sl.page) && (step != -sl.page))
{
step = 1;//其它值时强制设置成跳一步
}
adjust_scroll(&sl,step);
}
return 0;
}
void adjust_scroll(p_scroll scroll ,int len )
{
int top = scroll->top;
int cur = scroll->cur;
int page = scroll->page;
int count = scroll->count;
int step = len;
int next = cur + step;
int i = 0;
int page_turn = (len == page||len == -page)?1:0;//翻页标志
printf("page_turn:%d\n",page_turn);
int page_point = cur -top;
if(next < 0)//下一跳的位置 超过数据上边界0,同时说明是step=-1或-10
{
if(page_turn)//step = -10
{
top = ((top - page) < 0)?(count/page * page):(top - page);//此处可以不用判断,直接使用 top = count/page * page,因为当cur -page < 0时,top-page一定小于0
//cur = top ;
cur = ((top + (page-1)) < count)?(top + (page-1)):(count -1);//上翻页时,cur 定位到页内最后一项,此处判断的原因,count可能小于page,比如page=10,count=7(总数据小于一页的内容)
}
else//step = -1 说明上面没有数据了直接翻到尾页
{
top = count/page * page;
//cur = top ;
cur = count -1;//上翻页时,cur 定位到页内最后一项
}
}
else if(next < count)//下一跳的位置 在数据长度内
{
if(next <top)//向上翻页 说明step < 0
{
if(page_turn)//step = -10
{
//top = next/page * page;
top = ((top -page)<0)?0:(top -page);//此处判断的原因,cur -page >= 0 但是top-page不一定大于0,比如page=10,top=5 ,cur=12,
//top = top -page;
cur = ((top + page-1) < count)?(top + page-1):(count -1);//上翻页时,cur 定位到页内最后一项,此处可以不用判断,直接使用cur = ((top + page-1)
}
else//step = -1
{
top = ((top -1) < 0)?0:top-1;
cur = top;
}
}
else if(next < top + page) //页内 step = -1 or step = 1
{
top = top ;
cur = cur +step;
}
else //向下翻页
{
if(page_turn)//step = 10
{
//top = next/page * page;
top = top + page;
cur = top ;//下翻页时,cur 定位到页内第一项
}
else//step = 1
{
top = top + 1;
cur = ((cur+1)< count)?cur+1:count -1;//此处可以不用判断,直接使用cur = ((cur+1)
}
}
}
else //next>= count 下一跳的位置 超过数据下边界count
{
if(page_turn)//step = 10
{
top = ((top + page)< count)?(top + page):0;//下一跳的位置虽然超过了下边界,但是top可能不是最后一页的top ,比如count=23,page=10,top =10(位于第二页),cur= 18,此时如果换页next = cur + page = 18 + 10 > count
//但是后面还有一页,所以top = top + page = 10 + 10 = 20,然后再判断此时的top是否超过下边界,如果超过说明top 已经是最后一页的top 需要强制回到首页。
cur = top;
}
else//step = 1 说明下面没有数据了,直接会到首页
{
top = 0;
cur = top ;
}
}
//以下是测试打印
printf("step:%d,cur:%d,top=%d,next:%d,page:%d\n",step,cur,top,next,page);
for(i=0;i<count;i++)
{
if(cur == top && i == top)
{
printf("%d*********<-----top cur\n",i);
}
else if(i == top)
{
printf("%d*********<-----top\n",i);
}
else if(i== cur)
{
printf("%d*********<-----cur\n",i);
}
else
{
printf("%d*********\n",i);
}
}
scroll->top = top;
scroll->cur = cur;
}