Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

android - RecyclerView.ItemDecoration doesn't update after item is removed from RecyclerView.Adapter

My question

How can I get my ItemDecoration to "update" the item offsets for other views when I remove a given view from my adapter and then call notifyItemRemoved() ?

In my particular situation, I have an ItemDecoration that provides a small amount of top offset to every item, and a large amount of bottom offset to the last item only. When I remove the last item, the view that becomes the new last item does not have any bottom offset.

Before and after:

enter image description here enter image description here

If I then scroll the list around, when I return to the bottom of the list, my "new" last item has the correct offsets. It's only an issue for as long as the "new" last item remains visible on the screen.

What I've tried

If I change my notifyItemRemoved() call to notifyDataSetChanged(), the new last item will have the correct item offsets applied, but I lose the built-in animation I get from notifyItemRemoved().

If I keep using notifyItemRemoved() and additionally call notifyItemChanged() on the previous item, then I will get the correct item offsets but the animation is somewhat janky; the second-to-last item (before the removal) seems to fade out and then in again (in this screenshot, the card saying "item 19" was just removed):

enter image description here

I know that I can create a large space at the end of my list by applying bottom padding to my <RecyclerView> tag and specifying android:clipToPadding="false", but this solution is not acceptable for various reasons.

To reproduce

I originally encountered this issue in a much larger app I'm working on, but here's a tiny app that demonstrates the issue.

MainActivity.java:

public class MainActivity extends AppCompatActivity {

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

    final MyAdapter adapter = new MyAdapter(20);

    Button button = findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            adapter.removeItemAt(adapter.getItemCount() - 1);
        }
    });

    RecyclerView recycler = findViewById(R.id.recycler);
    recycler.setLayoutManager(new LinearLayoutManager(this));
    recycler.addItemDecoration(new MyItemDecoration());
    recycler.setAdapter(adapter);
}

private static class MyItemDecoration extends RecyclerView.ItemDecoration {

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int viewPosition = parent.getChildViewHolder(view).getLayoutPosition();
        int lastPosition = state.getItemCount() - 1;

        outRect.top = 20;
        outRect.bottom = (viewPosition == lastPosition) ? 200 : 0;
    }
}

private static class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

    private final List<String> list;

    private MyAdapter(int count) {
        this.list = new ArrayList<>();

        for (int i = 0; i < count; ++i) {
            list.add("" + i);
        }
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View itemView = inflater.inflate(R.layout.item, parent, false);
        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.text.setText("item: " + list.get(position));
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    private void removeItemAt(int position) {
        if (list.size() > 0) {
            list.remove(position);
            notifyItemRemoved(position);
        }
    }
}

private static class MyViewHolder extends RecyclerView.ViewHolder {

    private final TextView text;

    public MyViewHolder(View itemView) {
        super(itemView);
        this.text = itemView.findViewById(R.id.text);
    }
}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I solved this by changing my removeItemAt() method as follows:

private void removeItemAt(int position) {
    if (list.size() > 0) {
        list.remove(position);
        notifyItemRemoved(position);

        if (position != 0) {
            notifyItemChanged(position - 1, Boolean.FALSE);
        }
    }
}

The second argument to notifyItemChanged() is the key. It can be literally any object, but I chose Boolean.FALSE because it's a "well-known" object and because it conveys a little bit of intent: I don't want animations to run on the item I'm changing.

Why it works

It turns out that there's a second onBindViewHolder() method defined in RecyclerView.Adapter that I'd never seen before. From the source code:

public void onBindViewHolder(VH holder, int position, List<Object> payloads) {
    onBindViewHolder(holder, position);
}

Excerpted from that method's documentation:

The payloads parameter is a merge list from notifyItemChanged(int, Object) or notifyItemRangeChanged(int, int, Object). If the payloads list is not empty, the ViewHolder is currently bound to old data and Adapter may run an efficient partial update using the payload info. If the payload is empty, Adapter must run a full bind.

In other words, by passing something (anything) as a payload in notifyItemChanged(), we're telling the system that we want to perform only a "partial update" (in situations where that's possible).

So, sure, we've instructed the system to perform a partial update... but how does that stop the flickering caused by simply calling notifyItemChanged(position - 1) ? It has to do with the RecyclerView.ItemAnimator that's attached to all RecyclerViews by default: DefaultItemAnimator.

DefaultItemAnimator's source code includes this method:

@Override
public boolean canReuseUpdatedViewHolder(@NonNull ViewHolder viewHolder,
        @NonNull List<Object> payloads) {
    return !payloads.isEmpty() || super.canReuseUpdatedViewHolder(viewHolder, payloads);
}

You'll notice that this method also takes a List<Object> payloads parameter. This is the same list of payloads as used in the other onBindViewHolder() call mentioned above.

Because we passed a payload argument, this method will return true. And since the animator is now told that it can reuse the already-existing ViewHolder for our "changed" item, it doesn't tear it down and create a new one (or reuse a recycled one)... which stops the default fade animation on the changed item from running!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...