分页算法
分页的逻辑代码,实现滚动功能
-
思路
-
建立一个数组,如果想要在一个网页中显示n个页码,就将数组长度设置为n
-
使用Math.min( 当前页,总页数 )限制当前页的大小(当前页不能大于总页数)
-
给第一个页码begin和最后一个页码end赋初始值为1
-
判断begin和end在什么情况下取什么值,这里如果n为偶数,假设为6,那么判断条件就是
if (pageNow < 4) { end = Math.min(pageCount, 6); } else { begin = Math.min(pageNow - 3, pageCount - 5); end = Math.min(pageNow + 2, pageCount); } -
遍历数组
-
-
效果
-
代码
如下图所示(代码中一个网页显示的页数为奇数,这里是7,注意与叶顺为偶数时的区别)
public class PageBean<T> {
//当前页码
private int pageNow=1;
//每页显示记录数
private int pageSize=10;
//总记录数
private int rowCount;
//总页数
private int pageCount;
//列表
private List<T> userList;
//分页
private int[] pages;
public int getPageNow() {
return pageNow;
}
public void setPageNow(int pageNow) {
this.pageNow = pageNow;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getRowCount() {
return rowCount;
}
public void setRowCount(int rowCount) {
this.rowCount = rowCount;
}
public int getPageCount() {
if (rowCount % pageSize == 0) {
pageCount = rowCount / pageSize;
} else {
pageCount = rowCount / pageSize + 1;
}
return pageCount;
}
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
public List<T> getUserList() {
return userList;
}
public void setUserList(List<T> userList) {
this.userList = userList;
}
//分页算法
public int[] getPages() {
int pageNow = Math.min(getPageNow(), getPageCount());
int pageCount = getPageCount();
int begin = 1;
int end = 1;
if (pageNow < 4) {
end = Math.min(pageCount, 7);
} else {
begin = Math.min(pageNow - 3, pageCount - 6);
end = Math.min(pageNow + 3, pageCount);
}
begin=Math.max(1,begin);
int y = 0;
int[] pages = new int[end - begin + 1];
for (int i = begin; i <= end; i++) {
pages[y] = i;
y++;
}
return pages;
}
}