Android RecyclerView适配器:索引0处的notifyItemInserted和notifyItemMoved不起作用

时间:2016-09-25 03:57:37

标签: android

我有一个带有水平线性布局管理器的RecyclerView,声明如下:

RecyclerView graph = (RecyclerView) findViewById(R.id.graph);

RecyclerView.LayoutManager classManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
graph.setLayoutManager(classManager);
graph.addItemDecoration(new ComponentDecorator(this)); //Just sets a margin around each item

我有一个方法可以将占位符视图插入到RecyclerView中,如下所示:

private void insertPlaceholder(int index) {
    int placeholderIndex = getIndexOfPlaceholder(); //returns index of existing placeholder, -1 if none

    //No need to do anything
    if(placeholderIndex == index)
        return;

    if(placeholderIndex == -1) {
        ClassGraphItem placeholder = new ClassGraphItem();
        placeholder.setType(ClassGraphItem.PLACEHOLDER);

        mItems.add(index, placeholder);
        Print.log("notify item inserted at index", index);
        notifyItemInserted(index);
    }
    else {
        ClassGraphItem placeholder = mItems.get(placeholderIndex);
        mItems.remove(placeholderIndex);
        mItems.add(index, placeholder);

        notifyItemMoved(placeholderIndex, index);
    }
}

占位符只是一个不可见的视图,它模拟两个现有视图之间的空间开放:

private class PlaceholderViewHolder extends RecyclerView.ViewHolder {

    public PlaceholderViewHolder(View itemView) {
        super(itemView);

        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(mComponentWidth, 1);
        itemView.setLayoutParams(params);

        itemView.setVisibility(View.INVISIBLE);
    }

}

当插入的索引是> 0,它完美地运作。但是在索引0处,插入占位符或将现有占位符移动到0索引不起作用,特别是RecyclerView没有动画显示在索引0处插入的新项目。如果我使用notifyDataSetChanged()它工作。然而,这不是动画,也不是我正在寻找的效果。这对我来说似乎是个错误,但我想确保没有其他因素导致这个问题。

我正在使用最新版本的recyclerview支持库(24.2.1)。谢谢!

2 个答案:

答案 0 :(得分:15)

我删除了recycler.setHasFixedSize(true);,现在可以了。我不知道为什么这会有关系。

答案 1 :(得分:0)

由于设置recycler.setHasStableIds(true),然后使用项目的位置在适配器中分配getItemId,可能会发生这种情况。

这只会更新一个位置和其他项目不会被转移。