在ListView中交换项目动画

时间:2015-03-09 19:29:23

标签: android android-listview

在我的ListView中,当我点击一个Item时,我想在列表的末尾对它进行排序,而列表的其余部分应该通过向上滚动来填补空白。我已设法使用此代码为项目设置动画:

    public View getView(final int position, View convertView, final ViewGroup parent) {
        if (convertView == null) {
            convertView = mLayoutInflater
                    .inflate(R.layout.list_item_goal_content, null);
        }

    ...
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (animationRunning) {
                        return;
                    }

                    // only animate if item is not already at the end of list.
                    if (goals.indexOf(goal) != goals.size() - 1) {
                        int path = (getCount() - position) * animview.getHeight();

                        Animation animation = new TranslateAnimation(0, 0, 0, path);
                        animation.setDuration(700);


                        animation.setZAdjustment(Animation.ZORDER_TOP);
                        animation.setAnimationListener(new Animation.AnimationListener() {
                            @Override
                            public void onAnimationStart(Animation animation) {
                                animationRunning = true;
                            }

                            @Override
                            public void onAnimationEnd(Animation animation) {
                                animationRunning = false; 
                                // simply remove from its position and append to end 
                                goals.remove(goal);
                                goals.add(goal);
                                notifyDataSetChanged();
                            }

                            @Override
                            public void onAnimationRepeat(Animation animation) {                        }
                        });
                        convertView.startAnimation(animation);
                    }
                }
            });
        }
        return convertView;
    }

但我不知道如何滚动项目以填补空白。

1 个答案:

答案 0 :(得分:1)

最后我决定重建我的List并使用RecyclerView。它包含一个内置的ItemAnimator。我没有像我的问题中的代码那样开始自己的动画,而是简单地用它来交换项目:

// get position of the item to be moved
int indexOf = goals.indexOf(goal);
goals.remove(goal); // remove from its position
goals.add(goal);    // add to end of list
// Notify view about the move: it will handle the animation itself :)
notifyItemMoved(indexOf, goals.size()-1);

重建我的代码花了几个小时,但现在我很高兴不会停留在Listview上。