Advertisement
Tatarize

Animate Any Listview/Gridview changes.

Sep 17th, 2015
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.05 KB | None | 0 0
  1. //MIT license
  2.  
  3.  
  4. handleViewDatasetChange();
  5. swapElements(mBackingList, mMobileAdapterPosition, mMobileAdapterPosition + positionChange);
  6.  
  7.  
  8.  
  9. private static class IdLocator {
  10. public int left;
  11. public int top;
  12. public boolean visible;
  13.  
  14. public IdLocator(int left, int top, boolean visible) {
  15. this.left = left;
  16. this.top = top;
  17. this.visible = visible;
  18. }
  19. }
  20.  
  21. public void handleViewDatasetChange() {
  22. //THIS MUST BE CALLED PRIOR TO THE UNDERLYING CHANGES IN THE ADAPTER.
  23. //It saves the state, and calls the notify, and plugs in the predraw listener animations.
  24.  
  25. //Save the adapter state.
  26. final HashMap<Long,IdLocator> locations = new HashMap<>(getChildCount());
  27. int firstVisiblePosition = getFirstVisiblePosition();
  28. Adapter adapter = getAdapter();
  29. for (int i = 0, s = getChildCount(); i < s; i++) {
  30. View v = getChildAt(i);
  31. int position = firstVisiblePosition + i;
  32. long id = adapter.getItemId(position);
  33. locations.put(id, new IdLocator(v.getLeft(), v.getTop(), v.getVisibility() == View.VISIBLE));
  34. v.setVisibility(VISIBLE);
  35. }
  36.  
  37. ((BaseAdapter) getAdapter()).notifyDataSetChanged();
  38.  
  39.  
  40. final ViewTreeObserver observer = getViewTreeObserver();
  41. observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
  42. public boolean onPreDraw() {
  43. observer.removeOnPreDrawListener(this);
  44.  
  45. int firstVisiblePosition = getFirstVisiblePosition();
  46. Adapter adapter = getAdapter();
  47.  
  48. //Animate the changes from the saved states.
  49. for (int i = 0, s = getChildCount(); i < s; i++) {
  50. int position = firstVisiblePosition + i;
  51. long id = adapter.getItemId(position);
  52. IdLocator idLocator = locations.get(id);
  53. if (idLocator == null) continue;
  54.  
  55. View v = getChildAt(i);
  56.  
  57. if (!idLocator.visible) v.setVisibility(INVISIBLE);
  58. else v.setVisibility(VISIBLE);
  59.  
  60. int changeLeft = idLocator.left - v.getLeft();
  61. if (changeLeft != 0) {
  62. v.setTranslationX(changeLeft);
  63. Animator animatorX = ObjectAnimator.ofFloat(v, View.TRANSLATION_X, 0);
  64. animatorX.setDuration(MOVE_DURATION);
  65. animatorX.start();
  66. }
  67.  
  68. int changeTop = idLocator.top - v.getTop();
  69. if (changeTop != 0) {
  70. v.setTranslationY(changeTop);
  71. Animator animatorY = ObjectAnimator.ofFloat(v, View.TRANSLATION_Y, 0);
  72. animatorY.setDuration(MOVE_DURATION);
  73. animatorY.start();
  74. }
  75. }
  76. return true;
  77. }
  78. });
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement