问题
I have a listview, which shows 20 users initially. Whenever the listview bottom reaches a new REST API call will start and it shows more users(20,40,60 etc). When loading more users the list gets refreshed.
Listview items have a switch option and if I press the switch option the userid of that user is added to a list. If I again press the same switch that userid is removed from the list.
My problem is the selected user's switches are going to off state when loading more users. But the userids saved in the list have no problem, the list contains the selected user's id. So how can I on the switch of already selected users after loading more users?
回答1:
When receiving the users from your REST service, the state of every switch is false
. So you need to save your local list. Then you need to check with your primary key to see which users had state = true
.
Pseudo Code:
var oldUsersList = new List<User>(UsersList);
UsersList = await RestService.GetUsers();
foreach (var user in oldUsersList)
{
if (user.State)
{
UsersList.FirstOrDefault(u => u.UserId == user.UserId).State = true;
}
}
But you're doing Lazy Loading wrong!
The way you load new items completely destroys the reasons why you would want to do Lazy Loading at all. You want to do Lazy Loading (= Load when items are needed), because you don't need to load so much data at once. But you always load all items again.
What you should do is always only load 20 items. Then add these 20 items to your local list.
To do this, you need to be able to call your REST API with offset and limit as parameters.
For example: RestService.GetUsers(long offset, long limit)
- Load:
RestService.GetUsers(0, 20);
- Load:
RestService.GetUsers(20, 20);
- Load:
RestService.GetUsers(40, 20);
- Load:
RestService.GetUsers(60, 20);
Then you can add the result to your local list. Like this, you don't need to load users you already loaded in the past. Also by doing this, you don't have the problem with the state because your already loaded users don't change.
来源:https://stackoverflow.com/questions/52604115/xamarin-forms-current-listview-switch-state-changing-when-the-listview-gets-ref