android – 使用ViewHolder模式的适配器中的动画

前端之家收集整理的这篇文章主要介绍了android – 使用ViewHolder模式的适配器中的动画前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的适配器中使用动画时,我有问题.
  1. @Override
  2. public View getView(int position,View convertView,ViewGroup parent) {
  3.  
  4. if (convertView == null) {
  5. LayoutInflater inflater = LayoutInflater.from(context);
  6. convertView = inflater.inflate(resource,parent,false);
  7. holder = new ViewHolder();
  8.  
  9. holder.newRoomView = (TextView) convertView.findViewById(R.id.newRoom);
  10. convertView.setTag(holder);
  11. } else {
  12. holder = (ViewHolder) convertView.getTag();
  13. }
  14.  
  15. Room item = items.get(position);
  16.  
  17. // animate new rooms
  18. if (item.isNewRoom()) {
  19. AlphaAnimation alphaAnim = new AlphaAnimation(1.0f,0.0f);
  20. alphaAnim.setDuration(1500);
  21. alphaAnim.setAnimationListener(new AnimationListener() {
  22. public void onAnimationEnd(Animation animation) {
  23. holder.newRoomView.setVisibility(View.INVISIBLE);
  24. }
  25.  
  26. @Override
  27. public void onAnimationStart(Animation animation) {}
  28.  
  29. @Override
  30. public void onAnimationRepeat(Animation animation) {}
  31. });
  32. holder.newRoomView.startAnimation(alphaAnim);
  33. }
  34.  
  35. // ...
  36.  
  37. return convertView;
  38. }

在适配器外面添加一个新房间并调用notifyDataSetChanged新房间是正确的动画,但是当onAnimationEnd被调用时,另一个(不是新的房间)被隐藏.

有什么办法可以隐藏正确的房间吗?

解决方法

由于您尚未在getView()方法中声明持有人变量,我只能假设您已将其声明为类中的实例变量.这是你的问题.在动画完成时,变量持有人持有对完全不同的项目的引用.

您需要使用在getView()方法中声明为final的局部变量.我不知道在getView()方法之外是否需要这个持有者变量,但如果你这样做,你可以这样做:

  1. // animate new rooms
  2. if (item.isNewRoom()) {
  3. final ViewHolder holderCopy = holder; // make a copy
  4. AlphaAnimation alphaAnim = new AlphaAnimation(1.0f,0.0f);
  5. alphaAnim.setDuration(1500);
  6. alphaAnim.setAnimationListener(new AnimationListener() {
  7. public void onAnimationEnd(Animation animation) {
  8. holderCopy.newRoomView.setVisibility(View.INVISIBLE);
  9. }
  10.  
  11. @Override
  12. public void onAnimationStart(Animation animation) {}
  13.  
  14. @Override
  15. public void onAnimationRepeat(Animation animation) {}
  16. });
  17. holder.newRoomView.startAnimation(alphaAnim);
  18. }

这当然是不行的,如果动画需要这么长的时间,视图已被回收利用在此期间.

猜你在找的Android相关文章