Is it possible to have the last item in a RecyclerView to be docked to the bottom if there is no need to scroll?

后端 未结 4 1175
日久生厌
日久生厌 2021-02-08 17:35

I\'m building a shopping cart RecyclerView that displays all the items in the cart in a RecyclerView, as well as it has an additional view at the bottom that summarizes the cart

4条回答
  •  不知归路
    2021-02-08 18:15

    I was thinking about your task and eventually put together some code that you may find useful. There's a problem on this stage though.

    What I did is added an item decorator to a recycler view:

    recyclerView.addItemDecoration(new StickySummaryDecoration());
    

    And here's my implementation of the basic decorator (frankly, it's my first experience with item decorators, so it may not be optimal or totally correct but I did my best):

    public class StickySummaryDecoration extends RecyclerView.ItemDecoration {
    
        @Override
        public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
            int childCount = parent.getAdapter().getItemCount();
            int lastVisibleItemPosition =
                    ((LinearLayoutManager) parent.getLayoutManager()).findLastVisibleItemPosition();
            int firstVisiblePosition =
                    ((LinearLayoutManager) parent.getLayoutManager())
                            .findFirstCompletelyVisibleItemPosition();
            if ((firstVisiblePosition == 0) && (lastVisibleItemPosition == (childCount - 1))) {
                View summaryView = parent.getChildAt(parent.getChildCount() - 1);
                int topOffset = parent.getHeight() - summaryView.getHeight();
                int leftOffset =
                        ((RecyclerView.LayoutParams) summaryView.getLayoutParams()).leftMargin;
                c.save();
                c.translate(leftOffset, topOffset);
                summaryView.draw(c);
                c.restore();
                summaryView.setVisibility(View.GONE);
            }
        }
    }
    

    So what I get with this.

    Bottom-docked summary in the short list:

    Short list

    You need to scroll down to see the summary in the long list:

    Long list (you need to scroll down to see the summary element)

    Now about a problem. This side-effect when scrolling back up in the long list is what I haven't solved yet.

    problem

    My experiments are uploaded to a github repo just in case :)

    EDIT

    Just now I came to me that the missing row element in the recycler view is my recycled summary view holder that has GONE visibility. There should be a way to bring it back...

    EDIT 2

    I reconsidered my first solution and changed the code a little bit to account for the long list case (in which case the item decoration is disabled (I think it's closer to what you wanted to achieve)), this automatically resolves the missing row problem.

提交回复
热议问题