问题
i have a listview with 100 items and i want to display first 10 items and on click of next button i have to display next 10 ie.,from 11 to 20, i have the code for getting first 10 items
public int getCount() {
return 10;
}
but how to get next 10 items alone and so on. any idea
回答1:
One way to do this is,
1) Don't populate your ArrayList with all the data. Instead keep them in a separate ArrayList (al1
) and use an ArrayList (al2
) with max 10 values to use with your BaseAdapter.
2) Initially,
- al2 = al1[0] to al1[9]
- BaseAdatper(context, data)
3) Keep the BaseAdapter as it is but change
@Override
public int getCount() {
return 10;
}
to
@Override
public int getCount() {
return data.size();
}
It's not a must but it's good practice. Now you'll be showing only 10 items cause that's all you are passing to the adapter. Also write a public function in your extended BaseAdatper class to set the data
variable.
4) On the next button click event get the next 10 items from al1
and assign to al2
. Use the public function you wrote to over write data
with al2
.
5) BaseAdapter has a method called notifyDataSetChanged , call it. What this does is tell the adapter to refresh from top to bottom. Since you have data
over written with new data when the refresh occurs you'll be seeing the new data. That's it.
I don't think it'll be difficult for you to come up with a way to keep track from which index to which in al1
you're currently displaying. :)
回答2:
If you have 100 items, then just take the first 10 items for your adapter, and when the user presses next, get the next 10, and so on.
EDIT: On request for code, I can provide a simple example on how to do pagination.
int totalItems = 100;
int currentPage = 0;
int pageSize = 10;
int numPages = (int) Math.ceil((float) totalItems/pageSize);
ArrayList<String> items = new ArrayList<String>(totalItems);
List<String> page = items.subList(currentPage, pageSize);
Looking at the example above, given the number of items and the desired page size you can calculate how many pages you need to display, you can then select a sub list from your ArrayList. Each time the user presses next, increment the currentPage and refresh the adapter with the a new sub list.
来源:https://stackoverflow.com/questions/14869682/how-to-limit-list-items-display-in-listview-by-10-and-next-10after-clicking-next