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 1189
日久生厌
日久生厌 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条回答
  •  旧时难觅i
    2021-02-08 18:00

    Based on the answer by yigit I created a working implementation. Extend ItemDecoration and override getItemOffsets():

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int childCount = parent.getAdapter().getItemCount();
        if (parent.getChildLayoutPosition(view) != childCount - 1) return;
        int lastViewBottom = calculateViewBottom(parent.getLayoutManager().findViewByPosition(childCount - 2));
    
        view.measure(parent.getWidth(), parent.getHeight());
        int height = view.getMeasuredHeight();
        int topOffset = parent.getHeight() - lastViewBottom - height;
        if (topOffset < 0) topOffset = itemOffset;
    
        outRect.set(itemOffset, topOffset, itemOffset, itemOffset);
    }
    
    private int calculateViewBottom(View view) {
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
        return (int) view.getY() + view.getHeight() + params.topMargin + params.bottomMargin;
    }
    

提交回复
热议问题