如何在RecyclerView中使用ItemAnimator?

时间:2015-04-23 18:02:41

标签: android material-design android-recyclerview

我想在从recyclerview的适配器添加或删除项目时进行动画制作。我试图使用RecyclerView.ItemAnimator如下,但它不起作用..

    public class MyAnimator extends RecyclerView.ItemAnimator{

    @Override
    public boolean animateAdd(ViewHolder arg0) {
        Log.d("test","Added Animation");
        return false;
    }

    @Override
    public boolean animateChange(ViewHolder arg0, ViewHolder arg1, int arg2, int arg3, int arg4, int arg5) {
        Log.d("test","Change Animation");
        return false;
    }

    @Override
    public boolean animateMove(ViewHolder arg0, int arg1, int arg2, int arg3, int arg4) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean animateRemove(ViewHolder arg0) {
        Log.d("test", "Remove Animation");
        return false;
    }

    @Override
    public void endAnimation(ViewHolder arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void endAnimations() {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean isRunning() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void runPendingAnimations() {
        // TODO Auto-generated method stub

    }

}

我使用上面的代码如下。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

    data=new ArrayList<String>();   


    // use a linear layout manager
    mLayoutManager = new LinearLayoutManager(this);
    mRecyclerView.setLayoutManager(mLayoutManager);

    animator = new MyAnimator();
    mRecyclerView.setItemAnimator(animator);            

    mAdapter = new MyAdapter(data);
    mRecyclerView.setAdapter(mAdapter); 

}

每当我在数据集中添加一个新项目并调用mAdapter.notifyDataSetChanged()时,我希望MyAnimator类中存在animateAdd(ViewHolder arg0)中的日志;但它没有来......我错过了什么......为什么它不起作用。

1 个答案:

答案 0 :(得分:25)

首先,您不需要自定义ItemAnimator。您可以使用默认值,删除mRecyclerView.setItemAnimator(animator);

此外,您必须使用notifyItemInserted()notifyItemRemoved()代替notifyDataSetChanged(),它会为您调用适当的动画。