本文介绍了Java中的分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了分页逻辑:

我的要求:要显示的总元素:每页100个,如果我点击下一个它应该显示接下来的100个记录,如果我点击上一个100条记录。

My requirement: total elements to display:100 per page,if i click next it should display next 100 records,if i click previous 100 records.

初始可变值:


  • showFrom:1,

  • showTo:100

  • 最大元素:取决于数据大小。

  • pageSize:100。

  • showFrom:1,
  • showTo:100
  • max elements:depends on size of data.
  • pageSize:100.

代码:

if(paging.getAction().equalsIgnoreCase("Next")){
  paging.setTotalRec(availableList.size());
  showFrom = (showTo + 1);
  showTo = showFrom + 100- 1;
  if(showTo >= paging.getTotalRec())
    showTo = paging.getTotalRec();
  paging.setShowFrom(showFrom);
  paging.setShowTo(showTo);
}

else if(paging.getAction().equalsIgnoreCase("Previous")){
  showTo = showFrom - 1;
  showFrom = (showFrom - 100);
  paging.setShowTo(showTo);
  paging.setShowFrom(showFrom);
  paging.setTotalRec(availableList.size());
}

在这里,我可以删除元素并将其添加到现有数据。上面的代码可以正常工作很好,如果我添加和删除一些元素。但如果我一次删除或添加100个元素计数不正确显示上面的代码工作正常,如果我添加和删除一些元素。

Here i can remove and add the elements to the existing data.above code works fine if i add and remove few elements.but if i remove or add 100 elements at a time counts are not displaying properly above code works fine if i add and remove few elements.

推荐答案

要改进的一些事项:


  • 用<$ c替换magic值100 $ c> final int PAGE_SIZE = 100;

  • 将冗余代码分解出来。

  paging.setShowTo(showTo);
  paging.setShowFrom(showFrom);
  paging.setTotalRec(availableList.size());


到if / else之外以使你的逻辑更清晰

to outside of if/else to make your logic clearer


  • 确保前一个> = 0且下一个< =记录数

修改:

final int PAGE_SIZE = 100;
int numberOfPages = -1;
int currentPage = -1;

public void initializeVariables(){
  paging.setTotalRec(availableList.size());
  showFrom = 1; 
  showTo = PAGE_SIZE;
  //keep track of how many pages there should be
  numberOfPages = paging.getTotalRec()/PAGE_SIZE;
  currentPage = 1;
}

public void handlePagingAction(){
  if(paging.getAction().equalsIgnoreCase("Next")){
     if(currentPage < numberOfPages){
        ++currentPage;
     }
  }else if(paging.getAction().equalsIgnoreCase("Previous")){
     if(currentPage > 1){       
       --currentPage;
     }
  }      

  showFrom = (currentPage - 1) * PAGE_SIZE + 1;
  if(showFrom < 0){
    showFrom = 0
  }

  showTo = currentPage * PAGE_SIZE;
  if(showTo >= paging.getTotalRec()){
    showTo = paging.getTotalRec();
  }     

  paging.setShowTo(showTo);
  paging.setShowFrom(showFrom);
}

这篇关于Java中的分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 08:12