JMRboosties
JMRboosties

Reputation: 15740

Android RecyclerView Adapter: notifyItemInserted and notifyItemMoved at index 0 not working

I have a RecyclerView with a horizontal linear layout manager declared like this:

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

I have a method which inserts a placeholder view into the RecyclerView like this:

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);
    }
}

The placeholder is just an invisible view which simulates a space opening between two existing views:

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);
    }

}

When the inserted index is > 0, it works perfectly. However at index 0, either inserting a placeholder, or moving an existing placeholder to the 0 index does not work, specifically the RecyclerView doesn't animate to show the new item inserted at index 0. If I used notifyDataSetChanged() it does work. however that doesn't animate and isn't the effect I'm looking for. This seems like a bug to me, but I wanted to make sure there wasn't something else that was causing this issue.

I'm on the latest version of the recyclerview support library (24.2.1). Thanks!

Upvotes: 10

Views: 5789

Answers (2)

Shashank Bhushan
Shashank Bhushan

Reputation: 141

This may happen because of setting recycler.setHasStableIds(true) and then using item's position to assign the getItemId in the adapter.

This will just update that one position and other items won't be shifted as they have should.

Upvotes: 0

Abtin Gramian
Abtin Gramian

Reputation: 1780

I removed recycler.setHasFixedSize(true); and now it works. I have no idea why this would be related though.

Upvotes: 21

Related Questions