AccountAdapter.java 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* Copyright 2017 Andrew Dawson
  2. *
  3. * This file is a part of Tusky.
  4. *
  5. * This program is free software; you can redistribute it and/or modify it under the terms of the
  6. * GNU General Public License as published by the Free Software Foundation; either version 3 of the
  7. * License, or (at your option) any later version.
  8. *
  9. * Tusky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
  10. * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
  11. * Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License along with Tusky; if not,
  14. * see <http://www.gnu.org/licenses>. */
  15. package com.keylesspalace.tusky;
  16. import android.support.v7.widget.RecyclerView;
  17. import com.keylesspalace.tusky.entity.Account;
  18. import java.util.ArrayList;
  19. import java.util.List;
  20. abstract class AccountAdapter extends RecyclerView.Adapter {
  21. List<Account> accountList;
  22. AccountActionListener accountActionListener;
  23. AccountAdapter(AccountActionListener accountActionListener) {
  24. super();
  25. accountList = new ArrayList<>();
  26. this.accountActionListener = accountActionListener;
  27. }
  28. @Override
  29. public int getItemCount() {
  30. return accountList.size() + 1;
  31. }
  32. void update(List<Account> newAccounts) {
  33. if (newAccounts == null || newAccounts.isEmpty()) {
  34. return;
  35. }
  36. if (accountList.isEmpty()) {
  37. accountList = newAccounts;
  38. } else {
  39. int index = accountList.indexOf(newAccounts.get(newAccounts.size() - 1));
  40. for (int i = 0; i < index; i++) {
  41. accountList.remove(0);
  42. }
  43. int newIndex = newAccounts.indexOf(accountList.get(0));
  44. if (newIndex == -1) {
  45. accountList.addAll(0, newAccounts);
  46. } else {
  47. accountList.addAll(0, newAccounts.subList(0, newIndex));
  48. }
  49. }
  50. notifyDataSetChanged();
  51. }
  52. void addItems(List<Account> newAccounts) {
  53. int end = accountList.size();
  54. accountList.addAll(newAccounts);
  55. notifyItemRangeInserted(end, newAccounts.size());
  56. }
  57. public Account getItem(int position) {
  58. if (position >= 0 && position < accountList.size()) {
  59. return accountList.get(position);
  60. }
  61. return null;
  62. }
  63. }