Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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!

like image 216
JMRboosties Avatar asked Sep 25 '16 03:09

JMRboosties


1 Answers

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

like image 190
Abtin Gramian Avatar answered Oct 24 '22 16:10

Abtin Gramian